Mar*_*ona 6 python xml nested beautifulsoup
我正在尝试使用Beautifulsoup解析XML,但在尝试使用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>
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,book标签在book标签内重复,当我尝试执行以下操作时会导致错误:
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()
Run Code Online (Sandbox Code Playgroud)
正如你将看到的那样,在我的汤上.findAll我已经添加了recursive = false,理论上它不会通过找到的项目进行递归,但跳到下一个.
这似乎不起作用,因为我总是得到以下错误:
File "catalog.py", line 17, in rss_parser
print item.title.string
AttributeError: 'NoneType' object has no attribute 'string'
Run Code Online (Sandbox Code Playgroud)
我确定我在这里做了一些蠢事,如果有人能帮我解决这个问题,我会很感激.
更改HTML结构不是一个选项,此代码需要执行良好,因为它可能会解析大型XML文件.
soup.findAll('catalog', recursive=False)将返回一个仅包含顶级“目录”标签的列表。因为它没有“标题”孩子,所以item.title是None。
尝试soup.findAll("book")或soup.find("catalog").findChildren()替代。
编辑:好吧,问题不是我想的那样。尝试这个:
BSS.NESTABLE_TAGS["book"] = []
soup = BSS(open("catalog.xml"))
soup.catalog.findChildren(recursive=False)
Run Code Online (Sandbox Code Playgroud)