如何以正确的格式存储从 POST XML 请求收到的 XML? Python 请求库
我正在使用 Python requests 库向网站发送一个 XML 文件,并收到一堆 XML 代码(以字节格式),如下所示:
b'<?xml version="1.0" encoding="UTF-8"?>\n<GetCategorySpecificsResponse xmlns="urn:ebay:apis:eBLBaseComponents"><Timestamp>2022-03-15T09:54:41.461Z</Timestamp><Ack>Success</Ack><Version>1219</Version><Build>E1219_CORE_APICATALOG_19146446_R1</Build><Recommendations><CategoryID>19006</CategoryID><NameRecommendation>.....
但是,如何才能以正确的格式和所有正确的缩进获取上面的 xml ?我想将上面的字符串存储在另一个文件中,但是对于当前的字符串,它只是一条永远向右侧延伸的长线,这对我来说并不是真正有用......
下面是我的代码(以 r.content 作为上面的 xml):
import requests
xml_file = XML_FILE
headers = {'Content-Type':'text/xml'}
with open(XML_FILE) as xml:
r = requests.post(WEBSITE_URL, data=xml, headers=headers)
print(r.content)
new_file = open(ANOTHER_FILE)
new_file.write(str(r.content))
new_file.close()
我想存储在 new_file 中的 xml 示例:
<?xml version="1.0" encoding="UTF-8"?>
<GetCategorySpecificsResponse
xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2022-03-15T08:30:01.877Z</Timestamp>
<Ack>Success</Ack>
<Version>1219</Version>
<Build>E1219_CORE_APICATALOG_19146446_R1</Build>
<Recommendations>
<CategoryID>19006</CategoryID>
.....
</GetCategorySpecificsResponse>
谢谢!
I'm sending an XML file to a website with Python requests library and received back a bunch of XML code (in format of bytes) like below:
b'<?xml version="1.0" encoding="UTF-8"?>\n<GetCategorySpecificsResponse xmlns="urn:ebay:apis:eBLBaseComponents"><Timestamp>2022-03-15T09:54:41.461Z</Timestamp><Ack>Success</Ack><Version>1219</Version><Build>E1219_CORE_APICATALOG_19146446_R1</Build><Recommendations><CategoryID>19006</CategoryID><NameRecommendation>.....
However, how can I get the xml above in its correct format and with all the correct indentations? I want to store the string above in another file, but with the current string, it's just a long line going forever toward the right side that is not really useful to me...
Below is my code (with the r.content as the xml above):
import requests
xml_file = XML_FILE
headers = {'Content-Type':'text/xml'}
with open(XML_FILE) as xml:
r = requests.post(WEBSITE_URL, data=xml, headers=headers)
print(r.content)
new_file = open(ANOTHER_FILE)
new_file.write(str(r.content))
new_file.close()
Example of the xml I want to store in new_file:
<?xml version="1.0" encoding="UTF-8"?>
<GetCategorySpecificsResponse
xmlns="urn:ebay:apis:eBLBaseComponents">
<Timestamp>2022-03-15T08:30:01.877Z</Timestamp>
<Ack>Success</Ack>
<Version>1219</Version>
<Build>E1219_CORE_APICATALOG_19146446_R1</Build>
<Recommendations>
<CategoryID>19006</CategoryID>
.....
</GetCategorySpecificsResponse>
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种方法是通过解析器传递响应并保存到文件。例如,这样的事情应该有效:
One way to do it is to pass the response through a parser and save to file. For example, something like this should work: