我正在尝试使用提供的 HTML 抓取工具 here .它适用于他们提供的示例。但是,当我尝试将它与我的 webpage 一起使用时,我收到此错误 - 不支持带有编码声明的 Unicode 字符串。请使用未声明的字节输入或 XML 片段。
我试过谷歌搜索,但找不到解决方案。我真的很感激任何帮助。我想知道是否有办法使用 Python 将其复制为 HTML。
编辑:
from lxml import html
import requests
page = requests.get('http://cancer.sanger.ac.uk/cosmic/gene/analysis?ln=PTEN&ln1=PTEN&start=130&end=140&coords=bp%3AAA&sn=&ss=&hn=&sh=&id=15#')
tree = html.fromstring(page.text)
谢谢。
最佳答案
简答:使用 page.content
,而不是 page.text
。
来自 http://lxml.de/parsing.html#python-unicode-strings :
the parsers in lxml.etree can handle unicode strings straight away ... This requires, however, that unicode strings do not specify a conflicting encoding themselves and thus lie about their real encoding
来自 http://docs.python-requests.org/en/latest/user/quickstart/#response-content :
Requests will automatically decode content from the server [as
r.text
]. ... You can also access the response body as bytes [asr.content
].
如您所见,requests.text
和 lxml.etree
都想将 utf-8 解码为 unicode。但是如果我们让requests.text
做解码,那么xml文件里面的编码语句就变成了谎言。
所以,让 requests.content
不进行解码。这样 lxml
将收到一个一致未解码的文件。
关于python - 使用 lxml 和请求进行 HTML 抓取会导致 unicode 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023237/