在XML文档中搜索namesp中的元素

2024-04-30 01:45:14 发布

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

以下是我的代码:

import requests
import xml.etree.ElementTree as ET

r = requests.get("http://www.volcano.si.edu/news/WeeklyVolcanoRSS.xml")
tree = ET.fromstring(r.text.encode('utf-8'))
for pt in tree.findall('.//georss:point'):
    print (pt.text)

问题是:被视为前缀错误:

^{pr2}$

添加反斜杠以转义字符后:

for pt in tree.findall('.//georss\:point'):

…它会给出另一个错误:

SyntaxError: prefix 'georss\\' not found in prefix map

我该怎么做?在


Tags: 代码textinimportpttreeforprefix
2条回答

您需要通过向findall()方法添加参数来指定命名空间。试试这个:

import requests
import xml.etree.ElementTree as ET

r = requests.get("http://www.volcano.si.edu/news/WeeklyVolcanoRSS.xml")
tree = ET.fromstring(r.text.encode('utf-8'))
namespaces = {'georss' : 'http://www.georss.org/georss'}
for pt in tree.findall('.//georss:point', namespaces=namespaces):
    print (pt.text)

XML标记中的冒号是XML命名空间。在

请检查源文档中的属性,如xmlns:georss="<URL>"。URL是您的命名空间。在

参见:parse .xml with prefix's on tags? xml.etree.ElementTree

相关问题 更多 >