这是用于网络抓取 AAPL 的 Yahoo Finance 股票价格的 Python 3 代码。
import urllib.request
from bs4 import BeautifulSoup as bs4
htmlfile = urllib.request.urlopen("http://finance.yahoo.com/q?s=AAPL")
htmltext = htmlfile.read()
for price in htmltext.find(attrs={'id':"yfs_184_aapl"}):
print (price)
显然,代码在 Python 2.7 中几乎没有修改就可以正常工作。但是,它在 Python 3.3.3 Shell 中不起作用。这是它显示的错误:
Traceback (most recent call last):
File "C:/Python33/python codes/webstock2.py", line 8, in <module>
for price in htmltext.find(attrs={'id':"yfs_184_aapl"}):
TypeError: find() takes no keyword arguments
我已经学会了通过 str.encode 将字符串模式更正为二进制。我不确定我是否可以使用此代码。
Edit1:@Martijn 之后的最终工作代码更改
import urllib.request
from bs4 import BeautifulSoup as bs4
htmlfile = urllib.request.urlopen("http://finance.yahoo.com/q?s=AAPL")
htmltext = htmlfile.read()
soup = bs4(htmltext)
for price in soup.find_all(id="yfs_l84_aapl"):
print (price)
它打印出空白。你能想出这个吗。再次感谢。