如何遍历XML树而不必担心Python中的名称空间前缀?

2024-04-18 03:19:48 发布

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

例如,要读取RSS提要,这不起作用,因为在“item”之前插入了愚蠢的{http://purl.org…}名称空间:

#!/usr/bin/env python3
import xml.etree.ElementTree as ET
import urllib, urllib.request

url = "http://some/rss/feed"
response = urllib.request.urlopen(url)
xml_text = response.read().decode('utf-8')
xml_root = ET.fromstring(xml_text)
for e in xml_root.findall('item'):
  print("I found an item!")

既然findall()由于{}前缀而变得无用,下面是另一个解决方案,但这很难看:

#!/usr/bin/env python3
import xml.etree.ElementTree as ET
import urllib, urllib.request

url = "http://some/rss/feed"
response = urllib.request.urlopen(url)
xml_text = response.read().decode('utf-8')
xml_root = ET.fromstring(xml_text)
for e in xml_root:
  if e.tag.endswith('}item'):
    print("I found an item!")

我能让ElementTree把所有的前缀都扔掉吗?你知道吗


Tags: textimportenvhttpurlbinresponserequest