为了这以下 XML http://www.boardgamegeek.com/xmlapi/boardgame/13,如何获取 xml,然后解析它以获取值<age>
?
<boardgames>
<boardgame objectid="13">
<yearpublished>1995</yearpublished>
<minplayers>3</minplayers>
<maxplayers>4</maxplayers>
<playingtime>90</playingtime>
<age>10</age>
<name sortindex="1">Catan</name>
...
我目前正在尝试:
result = urlfetch.fetch(url=game_url)
xml = ElementTree.fromstring(result.content)
但我不确定我是否走在正确的道路上。当我尝试解析时出现错误(我认为是因为 xml 不是有效的 xml)。
xml.findtext('age')
or xml.findtext('boardgames/age')
通常会给你里面的10<age>10</age>
,但由于 xml 无效,解析似乎失败。ElementTree
根据我的经验,解析无效 xml 的工作相当糟糕。
而是使用美丽汤 http://www.crummy.com/software/BeautifulSoup/,它可以很好地处理无效的 xml。
content = urllib2.urlopen('http://boardgamegeek.com/xmlapi/boardgame/13').read()
soup = BeautifulSoup(content)
print soup.find('age').string
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)