python - 如何将动态值传递给 xml 文件?
问题描述
我们在 python 中使用 SOAP API。我们需要动态传递请求 xml 文件中的值。
test.xml
文件:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<Add xmlns="http://tempuri.org/">
<intA>3</intA>
<intB>4</intB>
</Add>
</Body>
</Envelope>
Python脚本:
from bs4 import BeautifulSoup
import requests
import xml.etree.ElementTree as ET
import lxml
url="http://www.dneonline.com/calculator.asmx?WSDL"
headers = {'content-type': 'text/xml'}
xmlfile = open('test.xml','r')
body = xmlfile.read()
response = requests.post(url,data=body,headers=headers)
print(response.text)
我们需要从 python 动态传递 intA 和 intB。
解决方案
您可以使用格式字符串方法。您可以在 xml 文件中指定位置/关键字参数。在进行请求调用时,您可以传递这些参数的值。
以下是您的 test.xml 文件的外观:
<Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
<Body>
<Add xmlns="http://tempuri.org/">
<intA>{first_number}</intA>
<intB>{second_number}</intB>
</Add>
</Body>
</Envelope>
在您的 Python 脚本中,您可以加载 xml 文件,并且在发出帖子请求时,可以传递参数。方法如下:
import requests
url = "http://www.dneonline.com/calculator.asmx?WSDL"
headers = {'content-type': 'text/xml'}
xmlfile = open('test.xml', 'r')
body = xmlfile.read()
response = requests.post(url, data=body.format(first_number=1, second_number=4), headers=headers)
print(response.text)
推荐阅读
- node.js - NodeJS 嵌套承诺
- php - 在 centos 的现有 apache 服务器(生产)上运行 laravel 项目
- javascript - 如何像在 IE 中一样在 Chrome 中禁用 A 超链接
- android - 在片段中比较两次不起作用
- reactjs - 如何在 Flatlist 中动态设置 react-native-material-menu
- python - 如何在仅包含列表中所有值的字典中查找所有键
- python - 执行makemigrations操作时出现Django“无法添加外键约束”错误
- python - 为什么 NLTK 的 PoS 标注器对单词中的每个字母进行标记,而不是对每个单词进行标记?
- javascript - 动态下载javascript并稍后执行
- eclipse - 行尾同居终端和 Eclipse Git