- 读取文本文件
在Python中,你可以使用内置的open()函数读取文本文件,然后循环处理每行数据。
import requests
with open('data.txt', 'r') as file:
- 如果你需要从文本文件中读取每行XML格式的数据,并将其作为参数发送POST请求,可以使用xml.etree.ElementTree库解析XML数据,然后通过requests库发送请求。假设你的XML数据可以直接作为请求体发送(具体取决于API要求),以下是一个示例:
import requests
import xml.etree.ElementTree as ET
with open('data.txt', 'r') as file:
for line in file:
root = ET.fromstring(line)
xml_data = ET.tostring(root, encoding='utf-8').decode('utf-8')
response = requests.post('http://your-api-url.com', data=xml_data, headers={'Content-Type': 'application/xml'})
if response.status_code == 200:
print("请求成功,响应内容:", response.text)
else:
print("请求失败,状态码:", response.status_code)
- 如果遇到请求文本内容过长被截取的情况,可以将内容转换为字节流,并将Content-Type设置为text/xml类型,以下为一个从文本中提取每行的指定内容作为参数,并发送post请求的完整示例:
import requests
import xml.etree.ElementTree as ET
import re
import time
with open('D:/data.txt', 'r', encoding='utf-8') as file:
for line in file:
match = re.search(r'<Message>(.*?)</Message>', line.strip())
if not match: continue
content = match.group(0)
root = ET.fromstring(content)
xml_data = ET.tostring(root, encoding='utf-8').decode('utf-8')
response = requests.post('http://your-api-url.com', data=xml_data.encode('utf-8'), headers={'Content-Type': 'text/xml'})
if response.status_code == 200:
print("请求成功,响应内容:", response.text)
else:
print("请求失败,状态码:", response.status_code)
time.sleep(2)