如何在googleappengin上解析Python中的xml

2024-04-25 02:29:52 发布

您现在位置:Python中文网/ 问答频道 /正文

对于这个following xml,我如何获取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>
  ...

我正在尝试:

^{pr2}$

但我不确定我走的路是对的。当我试图解析时,我得到了错误(我想是因为xml不是有效的xml)。在


Tags: nameage错误xmlfollowingobjectidcatanpr2
2条回答

xml.findtext('age')xml.findtext('boardgames/age')通常会得到<age>10</age>中的10,但是由于无效的xml,解析似乎失败了。^根据我的经验,{}在解析无效xml方面做得相当差。在

而是使用BeautifulSoup,它可以很好地处理无效的xml。在

content = urllib2.urlopen('http://boardgamegeek.com/xmlapi/boardgame/13').read()
soup = BeautifulSoup(content)
print soup.find('age').string

以下是我的工作:

import urllib2
from xml.etree import ElementTree

result = urllib2.urlopen('http://boardgamegeek.com/xmlapi/boardgame/13').read()
xml = ElementTree.fromstring(result)
print xml.findtext(".//age")

相关问题 更多 >