python - 使用 lxml 和请求进行 HTML 抓取会导致 unicode 错误

标签 python html unicode web-scraping lxml

我正在尝试使用提供的 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 [as r.content].

如您所见,requests.textlxml.etree 都想将 utf-8 解码为 un​​icode。但是如果我们让requests.text做解码,那么xml文件里面的编码语句就变成了谎言。

所以,让 requests.content 不进行解码。这样 lxml 将收到一个一致未解码的文件。

关于python - 使用 lxml 和请求进行 HTML 抓取会导致 unicode 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25023237/

相关文章:

javascript - 通过 JavaScript 将表格插入 div

unicode - 什么可以解释这种糟糕的字符编码?

python - 将月的数量平均分配到周 (2)

python - 如果服务器安全(使用 https),如何知道使用 Django

python - 如何自定义 Pandas 日期时间戳 @ x 轴

swift - 如果一个代码点序列构成一个 Unicode 字符,那么该序列的每个非空前缀是否也构成一个有效字符?

c++ - 为什么unicode编码需要函数wsetlocale()?

python - 从以 Python 方式出现的键列表中获取字典中的第一个值

javascript - 如何在 JavaScript 中正确使用引号?

javascript - 在执行点击事件之前显示弹出窗口