【问题标题】:BeautifulSoup 'AttributeError'BeautifulSoup '属性错误'
【发布时间】:2012-05-16 20:21:51
【问题描述】:

当我运行以下命令时,我收到“AttributeError: 'NoneType' object has no attribute '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]

【问题讨论】:

  • 这么多括号...我的眼睛受伤了。你真的需要阅读PEP8

标签: python beautifulsoup


【解决方案1】:
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 更好。

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    相关资源
    最近更新 更多