用python解析xml文档(在url上)

用python解析xml文档(在url上),python,xml,xml-parsing,xml.etree,Python,Xml,Xml Parsing,Xml.etree,我正在尝试使用请求解析xml文档(URL) 面临以下错误: ValueError: Unicode strings with encoding declaration are not supported 这是我的密码: import requests from lxml import etree from lxml.etree import fromstring req = requests.request('GET', "http://www.nbp.pl/kursy/xml/LastC.

我正在尝试使用请求解析xml文档(URL)

面临以下错误:

ValueError: Unicode strings with encoding declaration are not supported
这是我的密码:

import requests
from lxml import etree
from lxml.etree import fromstring

req = requests.request('GET', "http://www.nbp.pl/kursy/xml/LastC.xml")

a = req.text
b = etree.fromstring(a)
如何解析此xml。提前感谢您的帮助

您正在传递的是Unicode解码版本。不要这样做,XML解析器要求您传入原始字节

在此处使用
req.content
代替
req.text

a = req.content
b = etree.fromstring(a)
您还可以将XML文档流式传输到解析器:

req = requests.get("http://www.nbp.pl/kursy/xml/LastC.xml", stream=True)
req.raw.decode_content = True  # ensure transfer encoding is honoured
b = etree.parse(req.raw)

你看过这个帖子了吗@AlexeyGorozhanov我试过了。。不为我工作!扔一样的error@quikrr:如果您实际使用了
req.content
,则不可能引发相同的错误;你是否100%确定你在那里使用了正确的方法?