Python Requests for XML Data
If you are working with API requests that return XML data, you can use Python's requests module to make HTTP requests and parse the XML response. Here are a few ways to do it:
Method 1: Using requests.get() with xml.etree.ElementTree
First, you need to import the necessary modules:
import requests
import xml.etree.ElementTree as ET
Next, you can make an HTTP GET request using requests.get()
and store the response in a variable:
response = requests.get('https://example.com/api/data.xml')
Then, you can parse the XML response using ET.fromstring()
:
root = ET.fromstring(response.content)
Now, you can access the XML elements and attributes using root.findall()
and element.get()
:
for item in root.findall('item'):
title = item.find('title').text
category = item.get('category')
print(title, category)
Method 2: Using requests.get() with lxml.etree
If you prefer to use the lxml module for XML parsing, you can modify the code above as follows:
import requests
from lxml import etree
response = requests.get('https://example.com/api/data.xml')
root = etree.fromstring(response.content)
for item in root.findall('item'):
title = item.find('title').text
category = item.get('category')
print(title, category)
Note that you need to import etree
from lxml
instead of xml.etree.ElementTree
.
Method 3: Using requests.get() with xmltodict
If you prefer to work with XML data in dictionary format, you can use the xmltodict module:
import requests
import xmltodict
response = requests.get('https://example.com/api/data.xml')
data = xmltodict.parse(response.content)
for item in data['root']['items']['item']:
title = item['title']
category = item['@category']
print(title, category)
Note that you need to install the xmltodict
module using pip install xmltodict
.