【发布时间】:2024-10-15 12:45:02
【问题描述】:
我正在尝试使用 Beautifulsoup 解析 XML,但在尝试将“recursive”属性与 findall() 一起使用时碰壁了
我有一个非常奇怪的 xml 格式,如下所示:
<?xml version="1.0"?>
<catalog>
<book>
<author>Gambardella, Matthew</author>
<title>XML Developer's Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
<book>true</book>
</book>
<book>
<author>Ralls, Kim</author>
<title>Midnight Rain</title>
<genre>Fantasy</genre>
<price>5.95</price>
<publish_date>2000-12-16</publish_date>
<description>A former architect battles corporate zombies,
an evil sorceress, and her own childhood to become queen
of the world.</description>
<book>false</book>
</book>
</catalog>
如您所见,书标签在书标签内重复,当我尝试执行以下操作时会导致错误:
from BeautifulSoup import BeautifulStoneSoup as BSS
catalog = "catalog.xml"
def open_rss():
f = open(catalog, 'r')
return f.read()
def rss_parser():
rss_contents = open_rss()
soup = BSS(rss_contents)
items = soup.findAll('book', recursive=False)
for item in items:
print item.title.string
rss_parser()
如您所见,在我的 soup.findAll 中,我添加了 recursive=false,理论上它不会通过找到的项目递归,而是跳到下一个。
这似乎不起作用,因为我总是收到以下错误:
File "catalog.py", line 17, in rss_parser
print item.title.string
AttributeError: 'NoneType' object has no attribute 'string'
我确定我在这里做了一些愚蠢的事情,如果有人可以帮助我解决这个问题,我将不胜感激。
更改 HTML 结构不是一种选择,此代码需要执行良好,因为它可能会解析大型 XML 文件。
【问题讨论】:
标签: python xml nested beautifulsoup