1

当我运行以下命令时,我得到“AttributeError:'NoneType'对象没有属性'string'”。但是,当对块字符串变量执行相同的任务时;有用。

关于我做错了什么的任何想法?

from BeautifulSoup import BeautifulSoup
from urllib        import urlopen

url = ("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Albert%20Einstein&explaintext")

print ((BeautifulSoup(((urlopen(url)).read()))).find('extract').string).split("\n", 1)[0]
4

1 回答 1

0
from BeautifulSoup import BeautifulSoup
from urllib import urlopen
url = ("https://en.wikipedia.org/w/api.php?action=query&prop=extracts&titles=Albert%20Einstein&explaintext")

soup = BeautifulSoup(urlopen(url).read())
print soup.find('extract')  # returns None

find 方法没有找到带有“extract”标签的任何内容。如果你想看到它的工作,那么给它一个存在于文档中的 HTML 标签,比如“pre”或“html”

'extract' 看起来像一个 xml 标签。您可能想尝试阅读有关解析 XML 的 BeautifulSoup 文档 - http://www.crummy.com/software/BeautifulSoup/bs3/documentation.html#Parsing XML。还有一个新版本的 BeautifulSoup (bs4)。我发现 API 更好。

于 2012-05-16T12:21:51.147 回答