1

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

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'

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

4

1 回答 1

1

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

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

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

于 2012-10-18T18:04:15.533 回答