I am creating a web scrapping python code (using 2.7.11) that extracts the stock price using symbol. I am not sure why this is not working. But it gives me this output:
Enter Financial Symbol
appl YPE h
Do you want to run again?
My code is below:
import urllib
go=True
while go:
print "Enter Financial Symbol"
symbol=raw_input()
page=urllib.urlopen("http://finance.yahoo.com/q?s=" + symbol)
text=page.read()
where=text.find("yfs_l84")
start=where+7
end=start+5
result = text[start:end]
print ( symbol + " "+ result)
print "Do you want to run again?"
choice=raw_input()
if choice == "no":
go=False
How do I make it work?
You should not be using str.find to parse a webpage, you should use an html parser like bs4 but in this case there is an api that you can requests the data from in json format, combining with requests makes it pretty trivial to get the data.
You can pull whatever data you want using accessing by key which is a lot more robust than str.find.
The string
"yfs_l84"
you are searching for is not contained in the HTML returned by yahoo. Soleaves
where
to be-1
. So your slicetext[start:end]
will always betext[6:11]
and cutYPR h
out of the page source: