缩进xml数据获取通过请求python | |



我不知道如何实现它。

需要你的建议这如何实现在我的代码

My code:

import requests
url = '....'  # not mentioning as its private 
headers_details = {
'Host' : 'axb.vttp.com',
'Accept-Encoding' : 'gzip,deflate',
'Accept' : '*/*'
}
parameter = { 'id' : '4566' ,'key' :'tyuo' }
rq = requests.post( url,params=parameter, headers=headers_details) 
with open('demo.xml','w') as wr:
wr.write(rq.content)

我的数据写入我的xml文件。但它不缩进格式xml数据。

如何实现文件中xml数据的正确缩进格式

您需要解析xml,然后用缩进序列化它。

Withlxml:

from lxml import etree
import requests
url = r"https://www.w3schools.com/xml/note.xml"
rq = requests.get(url)
# Parse the xml
root = etree.fromstring(rq.content)
with open('demo.xml', 'wb') as wr:
# Serialise the xml
wr.write(etree.tostring(root, encoding="utf-8", pretty_print=True))

:

  • https://lxml.de/api/lxml.etree-module.html fromstring
  • https://lxml.de/api/lxml.etree-module.html tostring

最新更新