You can use a combination of ElementTree's fromstring() method and the requests module's requests.get() to accomplish this.

https://docs.python.org/2/library/xml.etree.elementtree.html#parsing-xml

fromstring() parses XML from a string directly into an Element, which is the root element of the parsed tree.

Install the requests module:

pip install requests

Use the requests.get() to get your xml file from the url as a string. Pass that into the fromstring() function.

import xml.etree.cElementTree as ET
import requests
tree = ET.fromstring(requests.get('http://synd.cricbuzz.com/j2me/1.0/livematches.xml').text)
for child in tree:
   print("%s - %s"%(child.get('srs'),child.get('mchDesc')))

Results:

None - None
India tour of Sri Lanka, 2015 - Cricbuzz Cup - SL vs IND
Australia tour of Ireland, 2015 - IRE vs AUS
New Zealand tour of South Africa, 2015 - RSA vs NZ
Royal London One-Day Cup, 2015 - SUR vs KENT
Royal London One-Day Cup, 2015 - ESS vs YORKS
Answer from Joe Young on Stack Overflow
🌐
Python
docs.python.org › 3 › library › xml.etree.elementtree.html
xml.etree.ElementTree — The ElementTree XML API
January 29, 2026 - Parses an XML document from a sequence of string fragments. sequence is a list or other sequence containing XML data fragments. parser is an optional parser instance. If not given, the standard XMLParser parser is used.
🌐
lxml
lxml.de › tutorial.html
The lxml.etree Tutorial
lxml.etree supports parsing XML in a number of ways and from all important sources, namely strings, files, URLs (http/ftp) and file-like objects. The main parse functions are fromstring() and parse(), both called with the source as first argument.
Discussions

Python - Parsing XML data with ElementTree - Stack Overflow
I am working on a module for my Discord bot which will get data from URL and sort it into embeds. I spent hours trying different methods to get it working and I managed to get it to display what I ... More on stackoverflow.com
🌐 stackoverflow.com
python - Trying to parse XML directly from a URL - Stack Overflow
import xml.etree.ElementTree as ET tree = ET.parse('https://data.cityofnewyork.us/api/views/25th-nujf/rows.xml') root = tree.getroot() for child in root: print(child.tag, child.attrib) for _id in root.findall('_id'): rank = _id.find('ethcty').text name = _id.get('cnt') print(name, rank) I am following the examples from the URL below. https://docs.python... More on stackoverflow.com
🌐 stackoverflow.com
python - Parsing a URL XML with the ElementTree XML API - Stack Overflow
Below is my sample code where in the background I am downloading statsxml.jsp with wget and then parsing the xml. My question is now I need to parse multiple XML URL and as you can see in the below... More on stackoverflow.com
🌐 stackoverflow.com
January 17, 2014
Parsing XML using Python ElementTree - Stack Overflow
I have an XML document in the following format The quick brown fox&... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Stack Overflow
stackoverflow.com › questions › 61667873 › python-parsing-xml-data-with-elementtree
Python - Parsing XML data with ElementTree - Stack Overflow
Below uses the built-in urllib moduel to parse XML from URL: Copyfrom urllib.request import urlopen import xml.etree.ElementTree as ET def vatbook_parse(url): with urlopen(url) as f: tree = ET.parse(f) root = tree.getroot() # CONDITIONALLY SET SEARCH PATH path = './/atcs/booking' if tree.find('atc') is None else './/atc' for atcs in root.iterfind(path): callsign = atcs.find('callsign') name = atcs.find('name') time_start = atcs.find('time_start') time_end = atcs.find('time_end') if callsign is not None: print(f"{name.text} booked {callsign.text} from {time_start.text} to {time_end.text}") First URL ·
🌐
DataCamp
datacamp.com › tutorial › python-xml-elementtree
Python XML Tutorial: Element Tree Parse & Read | DataCamp
December 10, 2024 - The XML file provided describes a basic collection of movies. The only problem is that the data is a mess! There have been many different curators of this collection, and everyone has their own way of entering data into the file. The main goal in this tutorial will be to read and understand the file with Python and then fix the problems. First, you need to read the file with ElementTree. tree = ET.parse('movies.xml') root = tree.getroot()
🌐
Python Forum
python-forum.io › thread-14239.html
XML parsing from URL
Hello I started my trek into Python a few days ago. I am receiving the following error: Quote:Please enter an XML URL to parse: http://py4e-data.dr-chuck.net/comments_42.xml Traceback (most recent call last): File '/home/lamidotijjo/Documents/Pyth...
Find elsewhere
Top answer
1 of 3
13

From ElementTree docs:

We can import this data by reading from a file:

import xml.etree.ElementTree as ET

tree = ET.parse('country_data.xml')
root = tree.getroot()

Or directly from a string:

root = ET.fromstring(country_data_as_string)

and later in the same page, 20.5.1.4. Finding interesting elements:

for neighbor in root.iter('neighbor'):
    print(neighbor.attrib)

Which translate to:

import xml.etree.ElementTree as ET

root = ET.fromstring("""
<root>
<H D="14/11/2017">
<FC>
    <F LV="0">The quick</F>
    <F LV="1">brown</F>
    <F LV="2">fox</F>
</FC>
</H>
<H D="14/11/2017">
<FC>
    <F LV="0">The lazy</F>
    <F LV="1">fox</F>
</FC>
</H>
</root>""")
# root = tree.getroot()
for h in root.iter("H"):
    print (h.attrib["D"])
for f in root.iter("F"):
    print (f.attrib, f.text)

output:

14/11/2017
14/11/2017
{'LV': '0'} The quick
{'LV': '1'} brown
{'LV': '2'} fox
{'LV': '0'} The lazy
{'LV': '1'} fox
2 of 3
4

You did not specifiy what exactly you whant to use so i recommend lxml for python. For getting the values you whant you have more possibiltys:

With a loop:

from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot()
text = []
for element in root:
   text.append(element.get('D',None))
     for child in element:
       for grandchild in child:
         text.append(grandchild.text)
print(text)

Output: ['14/11/2017', 'The quick', 'brown', 'fox', '14/11/2017', 'The lazy', 'fox']

With xpath:

from lxml import etree
tree = etree.parse('XmlTest.xml')
root = tree.getroot() 
D = root.xpath("./H")
F = root.xpath(".//F")

for each in D:
  print(each.get('D',None))

for each in F:
  print(each.text)

Output: 14/11/2017 14/11/2017 The quick brown fox The lazy fox

Both have there own advantages but give you a good starting point. I recommend the xpath since it gives you more freedom when values are missing.

Top answer
1 of 2
49

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

2 of 2
22

If I understand your question correctly:

for elem in doc.findall('timeSeries/values/value'):
    print elem.get('dateTime'), elem.text

or if you prefer (and if there is only one occurrence of timeSeries/values:

values = doc.find('timeSeries/values')
for value in values:
    print value.get('dateTime'), elem.text

The findall() method returns a list of all matching elements, whereas find() returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values element, in this case leading to the same result.

I don't see where the problem with not finding timeSeries comes from however. Maybe you just forgot the getroot() call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values or //timeSeries/values)

Top answer
1 of 4
6

Before I try to answer, a tip. Your exception handler covers up the nature of the problem. Just let the original exception rise up and you'll have more information to share with people who are interested in helping you.

I like to use feedparser to parse Atom feeds. It does indeed give you dict-like objects. I submitted a patch to feedparser 4.1 to parse the GeoRSS elements into GeoJSON style dicts. See https://code.google.com/p/feedparser/issues/detail?id=62 and blog post at http://sgillies.net/blog/566/georss-patch-for-universal-feedparser/. You'd use it like this:

>>> import feedparser
>>> feed = feedparser.parse("http://earthquake.usgs.gov/earthquakes/catalogs/1hour-M1.xml")
>>> feed.entries[0]['where']
{'type': 'Point', 'coordinates': (-122.8282, 38.844700000000003)}

My patched version of 4.1 is in my Dropbox and you can get it using pip.

$ pip install http://dl.dropbox.com/u/10325831/feedparser-4.1-georss.tar.gz

Or just download and install with "python setup.py install".

2 of 4
2

It's more comfortable to use lxml for XML processing. Here is an example that fetches the feed and prints earthquake titles and coordinates:

import lxml.etree

feed_url = 'http://earthquake.usgs.gov/earthquakes/catalogs/1hour-M1.xml'
ns = {
    'atom': 'http://www.w3.org/2005/Atom',
    'georss': 'http://www.georss.org/georss',
}

def main():
    doc = lxml.etree.parse(feed_url)
    for entry in doc.xpath('//atom:entry', namespaces=ns):
        [title] = entry.xpath('./atom:title', namespaces=ns)
        [point] = entry.xpath('./georss:point', namespaces=ns)
        print point.text, title.text

if __name__ == '__main__':
    main()
🌐
Edureka
edureka.co › blog › python-xml-parser-tutorial
Python XML Parser Tutorial | ElementTree and Minidom Parsing | Edureka
December 5, 2024 - In this Python XML Parser Tutorial, you will learn how to parse, read, modify and find elements from XML files in Python using ElementTree and Minidom.
🌐
GitHub
gist.github.com › MichelleDalalJian › f587530b6e0a72357541f39b2022aa55
Extracting Data from XML: The program will prompt for a URL, read the XML data from that URL using urllib and then parse and extract the comment counts from the XML data, compute the sum of the numbers in the file. · GitHub
('NoneType' object has no attribute 'text') import urllib.request, urllib.parse, urllib.error import ssl import xml.etree.ElementTree as ET ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE Value = input('Enter location: ') print('Retrieving',Value) uh = urllib.request.urlopen(Value, context=ctx) data = uh.read() data = data.decode() tree = ET.fromstring(data) counts = tree.findall('.//count') print('Retrieved',len(data),'characters') counter = 0 sum = 0 for elements in counts: counter += 1 sum = (elements.find('count').text) + sum print(counter) print(sum)
🌐
GitHub
github.com › luminati-io › parsing-xml-with-python
GitHub - luminati-io/parsing-xml-with-python: Parse XML in Python using ElementTree, lxml, SAX, and more for efficient data processing and structured data integration. · GitHub
Since it’s part of Python’s standard library, there’s no need for any additional installation. For instance, you can use the findall() method to retrieve all url elements from the root and print the text content of each loc element, like so:
Author   luminati-io
🌐
GeeksforGeeks
geeksforgeeks.org › xml-parsing-python
XML parsing in Python - GeeksforGeeks
June 28, 2022 - In this article, we will discuss how to scrap paragraphs from HTML using Beautiful Soup Method 1: using bs4 and urllib. Module Needed: bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files.
🌐
Stack Overflow
stackoverflow.com › questions › 72519781 › how-to-parse-xml-with-xml-etree-elementtree
python - How to parse XML with xml.Etree.ElementTree? - Stack Overflow
python · xml · xml-parsing · elementtree · pubmed · Share · Improve this question · Follow · edited Jun 6, 2022 at 17:19 · mzjn · 51.6k1616 gold badges141141 silver badges266266 bronze badges · asked Jun 6, 2022 at 15:16 · Hannes · 8322 gold badges22 silver badges88 bronze badges 4 · Try tree = ET.fromstring(response.content) LMC – LMC ·
🌐
Pynerds
pynerds.com › parsing-xml-in-python-with-etree-elementtree
Parsing xml in Python with etree.ElementTree
April 28, 2025 - import xml.etree.ElementTree as ... = "https://example.com/data.xml" with urllib.request.urlopen(url) as response: tree = ET.parse(response)...