0

For example, to read an RSS feed, this doesn't work because of the silly {http://purl.org ...} namespaces that get inserted before 'item':

#!/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!")

Now that findall() has been rendered useless because of the {} prefixes, here's another solution, but this is ugly:

#!/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!")

Can I get ElementTree to just trash all the prefixes?

wuxiekeji
  • 1,772
  • 2
  • 15
  • 22

1 Answers1

1

You need to handle namespaces as clearly explained at:

But, what if instead, you'll use a specialized library for reading RSS feeds, like feedparser:

>>> import feedparser
>>> url = "http://some/rss/feed"
>>> feed = feedparser.parse(url)

Though I would personally use an XMLFeedSpider Scrapy spider. As a bonus, you'll get all other Scrapy web-scraping framework features.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195