使用lxml和request进行HTML抓取会产生unicode错误

use*_*999 21 html python unicode lxml web-scraping

我正在尝试像这里提供的那样使用HTML scraper .它适用于他们提供的示例.但是,当我尝试在我的网页上使用它时,我收到此错误 - Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration. 我尝试使用Google搜索但无法找到解决方案.我真的很感激任何帮助.我想知道是否有办法使用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)
Run Code Online (Sandbox Code Playgroud)

谢谢.

Rob*_*obᵩ 52

简短回答:使用page.content,不是page.text.

来自http://lxml.de/parsing.html#python-unicode-strings:

lxml.etree中的解析器可以立即处理unicode字符串...但是,这要求unicode字符串本身不指定冲突编码,因此它们的实际编码是谎言

来自http://docs.python-requests.org/en/latest/user/quickstart/#response-content:

请求将自动解码来自服务器[as r.text]的内容....您还可以以字节[as r.content]的形式访问响应正文.

所以你看,两者requests.textlxml.etree希望将UTF-8解码为Unicode.但是如果我们让requests.text解码,那么xml文件中的编码语句就变成了谎言.

所以,我们requests.content不做解码.这种方式lxml将收到一致的未解码文件.