例如,要读取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把所有的前缀都扔掉吗?你知道吗
您需要处理名称空间,如下所述:
但是,如果相反,您将使用一个专门的库来阅读RSS提要,比如^{} :
虽然我个人会用^{} Scrapy spider 。作为奖励,您将获得所有其他Scrapy web-scraping framework features。你知道吗
相关问题 更多 >
编程相关推荐