我正在使用 Python 請求庫將 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>
謝謝!
uj5u.com熱心網友回復:
一種方法是通過決議器傳遞回應并保存到檔案。例如,這樣的事情應該可以作業:
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()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/444240.html
