我正在尝试使用这里提供的HTML scraper。对于他们提供的示例,它工作得很好。然而,当我尝试使用它与我的网页,我收到这个错误- Unicode strings with encoding declaration are not supported. Please use bytes input or XML fragments without declaration.
我试着用谷歌搜索,但找不到解决办法。我真的很感激你的帮助。我想知道是否有一种方法可以使用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
。
From http://lxml.de/parsing.html#python-unicode-strings:
lxml中的解析器。Etree可以直接处理unicode字符串…但是,这要求unicode字符串本身不指定冲突的编码,从而谎报它们的实际编码
From http://docs.python-requests.org/en/latest/user/quickstart/#response-content:
请求将自动解码来自服务器的内容[作为
r.text
]. ...您也可以以字节[asr.content
]访问响应体。
所以你看,requests.text
和lxml.etree
都想将utf-8解码为unicode。但是如果我们让requests.text
进行解码,那么xml文件中的编码语句就变成了一个谎言。
所以,让requests.content
不做解码。这样,lxml
将收到一个一致的未解码文件。