Skip to main content
 首页 » 编程设计

python之带有请求的 POST XML 文件

2025年05月04日13thcjp

我得到:

<error>You have an error in your XML syntax... 

当我运行这个我刚写的 python 脚本时(我是新手)

import requests 
 
xml = """xxx.xml""" 
 
headers = {'Content-Type':'text/xml'} 
 
r = requests.post('https://example.com/serverxml.asp', data=xml) 
 
print (r.content); 

这里是xxx.xml的内容

<xml> 
<API>4.0</API> 
<action>login</action> 
<password>xxxx</password> 
<license_number>xxxxx</license_number> 
<username>xxx@xyz.com</username> 
<training>1</training> 
</xml> 

我知道 xml 是有效的,因为我将相同的 xml 用于 perl 脚本并且正在打印回内容。

任何帮助将不胜感激,因为我是 python 的新手。

请您参考如下方法:

您想将文件中的 XML 数据提供给 requests.post。但是,此功能不会为您打开文件。它希望您向它传递一个文件对象,而不是文件名。您需要在调用 requests.post 之前打开该文件。

试试这个:

import requests 
 
# Set the name of the XML file. 
xml_file = "xxx.xml" 
 
headers = {'Content-Type':'text/xml'} 
 
# Open the XML file. 
with open(xml_file) as xml: 
    # Give the object representing the XML file to requests.post. 
    r = requests.post('https://example.com/serverxml.asp', data=xml, headers=headers) 
 
print (r.content);