gpt4 book ai didi

python - 如何将动态值传递给 xml 文件?

转载 作者:行者123 更新时间:2023-12-02 03:24:35 24 4
gpt4 key购买 nike

我们正在使用 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文件,并且在发出posts请求时,可以传递参数。方法如下:

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)

关于python - 如何将动态值传递给 xml 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53760429/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com