【问题标题】:Python decoding errors with BeautifulSoup, requests, and lxmlBeautifulSoup、requests 和 lxml 的 Python 解码错误
【发布时间】:2012-10-09 06:33:57
【问题描述】:

我正在尝试从一个流行的基于浏览器的游戏中提取一些数据,但遇到了一些解码错误:

import requests
from bs4 import BeautifulSoup

r = requests.get("http://www.neopets.com/")
p = BeautifulSoup(r.text)

这会产生以下堆栈跟踪:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "build/bdist.linux-x86_64/egg/bs4/__init__.py", line 172, in __init__

File "build/bdist.linux-x86_64/egg/bs4/__init__.py", line 185, in _feed

File "build/bdist.linux-x86_64/egg/bs4/builder/_lxml.py", line 195, in feed
File "parser.pxi", line 1187, in lxml.etree._FeedParser.close    (src/lxml/lxml.etree.c:87912)
File "parsertarget.pxi", line 130, in lxml.etree._TargetParserContext._handleParseResult (src/lxml/lxml.etree.c:97055)
File "lxml.etree.pyx", line 294, in lxml.etree._ExceptionContext._raise_if_stored (src/lxml/lxml.etree.c:8862)
File "saxparser.pxi", line 274, in lxml.etree._handleSaxCData (src/lxml/lxml.etree.c:93385)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xb1 in position 476: invalid start byte

执行以下操作:

print repr(r.text[476 - 10: 476 + 10])

生产:

u'ttp-equiv="X-UA-Comp'

我真的不确定这里的问题是什么。任何帮助是极大的赞赏。谢谢。

【问题讨论】:

  • 您是否尝试过使用r.content 代替? BeautifulSoup 为您解码,但 r.text 返回 Unicode。
  • 在下面查看我的评论。这似乎也失败了。

标签: python beautifulsoup lxml decoding python-requests


【解决方案1】:

.text 响应返回一个解码后的 unicode 值,但也许你应该让 BeautifulSoup 为你解码:

p = BeautifulSoup(r.content, from_encoding=r.encoding)

r.content 返回未解码的原始字节串,r.encoding 是从标头中检测到的编码。

【讨论】:

  • >>> p = BeautifulSoup(r.content) Traceback (最近一次调用最后一次): ... UnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 0: invalid continuation byte
  • @user1622821:顺便说一句,我无法重现您对该 URL 的问题。你的例子对我有用,我的也一样。
  • 这与我的本地安装有关吗?我在 CrunchBang 上运行 Python 2.6.6,并安装了最新版本的 libxml 和 libxslt。我用 easy_install 安装了 BeautifulSoup4、requests 和 lxml。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-07
  • 2018-04-02
  • 2017-03-19
  • 1970-01-01
  • 1970-01-01
  • 2016-12-28
  • 2011-08-19
相关资源
最近更新 更多