如何以正确的格式存储从 POST XML 请求收到的 XML? Python 请求库

How to store XML received from POST XML request in its correct format? Python requests library

我将一个 XML 文件发送到一个带有 Python 请求库的网站,并收到了一堆 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>

谢谢!

一种方法是通过解析器传递响应并保存到文件。例如,像这样的东西应该可以工作:

from bs4 import BeautifulSoup as bs
soup= bs(r.text,"lxml")
with open("file.xml", "w", encoding='utf-8') as file:
    file.write(str(soup.prettify()))