Reputation: 232
I am a beginner to concepts of ElementTree in python. I created a simple program to extract some information from a xml file which was saved on my local computer.
import xml.etree.cElementTree as ET
tree = ET.ElementTree(file='cricket.xml')
root = tree.getroot()
for child in root:
print("%s - %s"%(child.get('srs'),child.get('mchDesc')))
Now, I want to use a xml file from a certain web address and extract information from that file. How can I do that without saving that file on local computer?
Upvotes: 1
Views: 4574
Reputation: 5875
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
Upvotes: 4