您不应该使用 str.find 来解析网页,而应该使用像 bs4 这样的 html 解析器,但在这种情况下,您可以使用 api 请求 json 格式的数据,并结合 requests让获取数据变得非常简单。
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 更强大。