2012-10-18 177 views
1

我试图拉一些数据从一个流行的基于浏览器的游戏,Python的解码错误,但我有一些解码错误麻烦:与BeautifulSoup,请求和LXML

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' 

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

+0

您是否尝试过使用'r.content'? BeautifulSoup为你解码,但'r.text'返回Unicode。 –

+0

请参阅下面的评论。这似乎也失败了。 –

回答

1

.text一个响应返回解码Unicode值,但也许你应该让BeautifulSoup做解码为您提供:

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

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

+0

>>> P = BeautifulSoup(r.content) 回溯(最近通话最后一个): ... 的UnicodeDecodeError:无效延续字节 –

+0

@ user1622821:在位置0 'utf-8' 编解码器不能解码字节0xd0我不能用这个URL重现你的问题,顺便说一句。你的例子适用于我,我的例子也是如此。 –

+0

这是否与我的本地安装有关?我在CrunchBang上运行Python 2.6.6,并安装了最新版本的libxml和libxslt。我使用easy_install安装了BeautifulSoup4,请求和lxml。 –