Python 网络抓取-如何提取股票价格

Python 网络抓取-如何提取股票价格,python,python-2.7,web-scraping,Python,Python 2.7,Web Scraping,我正在创建一个web抓取python代码(使用2.7.11),该代码使用符号提取股票价格。我不知道这为什么不起作用。但它给了我这个输出: Enter Financial Symbol appl YPE h Do you want to run again? 我的代码如下: import urllib go=True while go: print "Enter Financial Symbol" symbol=raw_input() page

我正在创建一个web抓取python代码(使用2.7.11),该代码使用符号提取股票价格。我不知道这为什么不起作用。但它给了我这个输出:

Enter Financial Symbol

appl YPE h
Do you want to run again?
我的代码如下:

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
如何使其工作?

您正在搜索的字符串“yfs_l84”不包含在yahoo返回的HTML中。所以

where=text.find("yfs_l84")
中的
保留为
-1
。因此,您的切片
text[start:end]
将始终是
text[6:11]
并从页面源代码中剪切
YPR h

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

...

您不应该使用str.find来解析网页,您应该使用类似的html解析器,但在本例中,有一个api,您可以请求json格式的数据,与之相结合可以使获取数据变得非常简单

In [25]: import  requests

In [26]: sym = "DVN"    
In [27]: r = requests.get("http://finance.yahoo.com/webservice/v1/symbols/{sym}/quote?format=json".format(sym=sym)) 
In [28]: r.json()
Out[28]: 
{'list': {'meta': {'count': 1, 'start': 0, 'type': 'resource-list'},
  'resources': [{'resource': {'classname': 'Quote',
     'fields': {'name': 'Devon Energy Corporation Common',
      'price': '18.650000',
      'symbol': 'DVN',
      'ts': '1455915714',
      'type': 'equity',
      'utctime': '2016-02-19T21:01:54+0000',
      'volume': '33916489'}}}]}}

In [29]: sym = "YHOO"
In [30]: r = requests.get("http://finance.yahoo.com/webservice/v1/symbols/{sym}/quote?format=json".format(sym=sym))
In [31]: r.json()
Out[31]: 
{'list': {'meta': {'count': 1, 'start': 0, 'type': 'resource-list'},
  'resources': [{'resource': {'classname': 'Quote',
     'fields': {'name': 'Yahoo! Inc.',
      'price': '30.040001',
      'symbol': 'YHOO',
      'ts': '1455915600',
      'type': 'equity',
      'utctime': '2016-02-19T21:00:00+0000',
      'volume': '20734985'}}}]}}

In [32]: sym = "AAPL"
In [33]: r = requests.get("http://finance.yahoo.com/webservice/v1/symbols/{sym}/quote?format=json".format(sym=sym))
In [34]: r.json()
Out[34]: 
{'list': {'meta': {'count': 1, 'start': 0, 'type': 'resource-list'},
  'resources': [{'resource': {'classname': 'Quote',
     'fields': {'name': 'Apple Inc.',
      'price': '96.040001',
      'symbol': 'AAPL',
      'ts': '1455915600',
      'type': 'equity',
      'utctime': '2016-02-19T21:00:00+0000',
      'volume': '35374173'}}}]}}
您可以使用比str.find更健壮的键访问来提取任何您想要的数据