【问题标题】:HTML scraping using lxml and requests gives a unicode error [duplicate]使用 lxml 和请求进行 HTML 抓取会产生 unicode 错误 [重复]
【发布时间】:2014-09-21 07:01:57
【问题描述】:

我正在尝试使用像here 提供的 HTML 抓取工具。它适用于他们提供的示例。但是,当我尝试将它与 webpage 一起使用时,我收到此错误 - 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)

谢谢。

【问题讨论】:

  • 请将您的抓取工具减少到仍然显示错误的最小程序,并将该短程序复制粘贴到您的问题中。请参阅stackoverflow.com/help/mcve 了解更多信息。
  • @Robᵩ 我已经添加了代码,但错误仍然相同:不支持带有编码声明的 Unicode 字符串。请使用未声明的字节输入或 XML 片段。

标签: python html unicode web-scraping lxml


【解决方案1】:

简答:使用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 解码为 un​​icode。但是如果我们让requests.text去解码,那么xml文件里面的编码语句就变成了谎言。

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

【讨论】:

  • 这有帮助。谢谢。
  • 效果很好,谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-08
  • 1970-01-01
  • 2019-03-12
  • 2018-02-22
  • 2019-01-16
  • 2022-01-13
相关资源
最近更新 更多