Python请求包:处理xml响应

我非常喜欢这个requests包和处理JSON响应的舒适方式。

不幸的是,我不明白我是否也可以处理XML响应。 有谁有经验如何处理requests包的XML响应? 是否有必要在XML解码中包含另一个如urllib2包?

requests不处理parsingXML响应,不。 XML响应本质上比JSON响应复杂得多,您如何将XML数据序列化到Python结构中并不那么简单。

Python带有内置的XMLparsing器。 我build议你使用ElementTree API :

 import requests from xml.etree import ElementTree response = requests.get(url) tree = ElementTree.fromstring(response.content) 

或者,如果回答特别大,则使用增量方法:

 response = requests.get(url, stream=True) # if the server sent a Gzip or Deflate compressed response, decompress # as we read the raw stream: response.raw.decode_content = True events = ElementTree.iterparse(response.raw) for event, elem in events: # do something with `elem` 

外部的lxml项目build立在相同的API上,为您提供更多function。