【问题标题】:parse xml document (on url) in python [duplicate]在python中解析xml文档(在url上)[重复]
【发布时间】:2015-04-04 11:38:17
【问题描述】:

我正在尝试使用请求解析 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 解析。在此先感谢您的帮助

【问题讨论】:

  • 你看过这篇文章了吗? stackoverflow.com/questions/15830421/…
  • @AlexeyGorozhanov 我试过了.. 不适合我!抛出同样的错误
  • @quikrr:如果你实际使用req.content,它不可能抛出同样的错误;您是否 100% 确定您在那里使用了正确的方法?

标签: python xml xml-parsing xml.etree


【解决方案1】:

您正在传递 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)

【讨论】:

    猜你喜欢
    • 2016-01-27
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-17
    • 2013-03-04
    相关资源
    最近更新 更多