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

Viewed 94

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!

1 Answers

One way to do it is to pass the response through a parser and save to file. For example, something like this should work:

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()))
Related