簡體   English   中英

縮進通過請求獲取的 xml 數據 | 蟒蛇 |

[英]Indent xml data fetched via request | python |

我被卡住了,不知道如何實現它。

需要您對如何在我的代碼中實現的建議

我的代碼:

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,然后使用縮進對其進行序列化。

使用lxml

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

看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM