怎么在Python中发送XML请求并解析响应?
时间: 2024-12-17 21:48:28 浏览: 5
在Python中,你可以使用标准库如`urllib.request`模块来发送XML请求,然后使用像`xml.etree.ElementTree`这样的库来解析响应。以下是基本步骤:
1. 导入所需的模块:
```python
import urllib.request
from xml.etree import ElementTree as ET
```
2. 构造XML数据(如果请求体包含XML):
```python
xml_data = """
<request>
<param1>value1</param1>
<param2>value2</param2>
</request>
"""
```
3. 创建一个`HTTPHandler`,这将用于发送POST请求:
```python
def send_request(url, data):
request = urllib.request.Request(url, data=data.encode('utf-8'))
request.add_header('Content-Type', 'application/xml')
return urllib.request.urlopen(request)
url = 'http://your-api-url.com'
response = send_request(url, xml_data)
```
4. 解析XML响应:
```python
xml_response = response.read()
root = ET.fromstring(xml_response)
# 获取元素值
result_value = root.find('.//response').text
# 或者遍历整个树获取元素
for child in root:
print(child.tag, child.text)
```
5. 检查错误(如果有错误响应):
```python
if response.getcode() != 200:
print(f"Error: {response.status} - {response.reason}")
```
阅读全文