I wrote the code that would scrape Finviz for tickers and href
that attach to the ticker. I tested with multi-page as well as one page. I'm new to Python programming and therefore believe my code is terrible. I'm hoping someone would help me review it and point out ways to improve it. My goal is to have the code more scalable than what I have now.
import bs4 as bs
import requests
class finviz_crawler():
def requesting(self,type):
items=1
baseurl='https://finviz.com/screener.ashx?v=111'
if type == 'sp500':
firstpage=baseurl+'&f=idx_sp500&o=ticker'
elif type == "China":
firstpage=baseurl+'&f=cap_largeover,geo_china'
finalurl=firstpage
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'}
resp=requests.get(finalurl,headers=headers)
soup = bs.BeautifulSoup(resp.text,"lxml")
table=soup.findAll('td',{'class':'screener-body-table-nw'})
maxpage_a_tag=[]
maxpage_td=soup.findAll('td',{'class':'body-table'},bgcolor="#ffffff",valign="top",width="100%")
tickerdict={}
for tags in maxpage_td[0].findAll('a'):
maxpage_a_tag.append(tags)
if not maxpage_a_tag:
maxpage=1
elif (maxpage_a_tag[-1].text=="next"):
maxpage=maxpage_a_tag[-2].text
else:
maxpage=maxpage_a_tag[-1].text
for page in range(int(maxpage)):
resp=requests.get(finalurl,headers=headers)
soup = bs.BeautifulSoup(resp.text,"lxml")
table=soup.findAll('td',{'class':'screener-body-table-nw'})
for row in table:
ticker_rows=row.findAll('a',{'class':'screener-link-primary'},href=True)
for tickers in ticker_rows:
tickerdict[tickers.text]=tickers['href']
items+=20
finalurl="{}{}{}".format(firstpage,"&r=",str(items))
print(tickerdict)
Call the class using finviz_crawler().requesting('China')