1

这是用于网络抓取 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)

它打印出空白。你能想出这个吗。再次感谢。

4

1 回答 1

3

你在打电话str.find()不是 BeautifulSoup.find()。你忘记了一些东西:

soup = bs4(htmltext)

for price in soup.find(attrs={'id':"yfs_184_aapl"}):

但是如果你要循环,你需要调用find_all(),真的:

for price in soup.find_all(id="yfs_l84_aapl"):

您实际上不必使用attrs关键字参数;直接将属性指定为关键字参数也可以正常工作。

必须使用正确的id属性;它是yfs_l84_aapl(字母l,后跟数字84),而不是数字1

于 2014-01-02T15:00:16.590 回答