Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
304 views
in Technique[技术] by (71.8m points)

python - Web Scraping - how to extract stock price

I am creating a web scraping 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The string "yfs_l84" you are searching for is not contained in the HTML returned by yahoo. So

where=text.find("yfs_l84")

leaves where to be -1. So your slice text[start:end] will always be text[6:11] and cut YPR h out of the page source:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-US">
<head>
    ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...