-
Notifications
You must be signed in to change notification settings - Fork 16
/
Finviz-Scraper.py
53 lines (44 loc) · 1.61 KB
/
Finviz-Scraper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import requests
from bs4 import BeautifulSoup
import pandas as pd
import progressbar
def scrape_finviz(symbols):
# Get Column Header
req = requests.get("https://finviz.com/quote.ashx?t=MSFT")
soup = BeautifulSoup(req.content, 'html.parser')
table = soup.find_all(lambda tag: tag.name=='table')
rows = table[9].findAll(lambda tag: tag.name=='tr')
out=[]
for i in range(len(rows)):
td=rows[i].find_all('td')
out=out+[x.text for x in td]
ls=['Ticker','Sector','Sub-Sector','Country']+out[::2]
dict_ls={k:ls[k] for k in range(len(ls))}
df=pd.DataFrame()
p = progressbar.ProgressBar()
p.start()
for j in range(len(symbols)):
p.update(j/len(symbols) * 100)
req = requests.get("https://finviz.com/quote.ashx?t="+symbols[j])
if req.status_code !=200:
continue
soup = BeautifulSoup(req.content, 'html.parser')
table = soup.find_all(lambda tag: tag.name=='table')
rows=table[6].findAll(lambda tag: tag.name=='tr')
sector=[]
for i in range(len(rows)):
td=rows[i].find_all('td')
sector=sector+[x.text for x in td]
sector=sector[2].split('|')
rows = table[9].findAll(lambda tag: tag.name=='tr')
out=[]
for i in range(len(rows)):
td=rows[i].find_all('td')
out=out+[x.text for x in td]
out=[symbols[j]]+sector+out[1::2]
out_df=pd.DataFrame(out).transpose()
df=df.append(out_df,ignore_index=True)
p.finish()
df=df.rename(columns=dict_ls)
return(df)
data=scrape_finviz(['META','MSFT','BABA','TSLA''])