从这个网站http://engine.data.cnzz.com/main.php?s=engine&uv=&st=2014-03-01&et=2014-03-31
<tr class="list03" onclick="showMen1(9);" style="cursor:pointer;">
<td id="e_9" class="qh_one">百度汇总</td>
我在抓取文本,想让百度汇总
但是当我r.encoding = 'utf-8'
时,结果是�ٶȻ���
如果我不使用utf-8
,结果就是°Ù¶È»ã×Ü
发布于 2014-04-24 12:19:22
服务器在响应头中没有告诉您任何有用的信息,但是HTML页面本身包含:
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
GB2312是一种可变宽度的编码,类似于UTF-8.然而,页面是存在的;实际上它使用了GBK,这是GB2312的一个扩展。
您可以很好地用GBK解码它:
>>> len(r.content.decode('gbk'))
44535
>>> u'百度汇总' in r.content.decode('gbk')
True
使用gb2313
解码失败:
>>> r.content.decode('gb2312')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'gb2312' codec can't decode bytes in position 26367-26368: illegal multibyte sequence
但是,由于GBK是GB2313的超集,所以即使指定了前者,使用前者也应该是安全的。
如果使用requests
,则将r.encoding
设置为gb2312
有效,因为r.text
在处理解码错误时使用replace
:
content = str(self.content, encoding, errors='replace')
因此,使用GB2312时的解码错误仅用于GBK中定义的编码点。
请注意,BeautifulSoup可以自己完成解码;它将找到meta
头:
>>> soup = BeautifulSoup(r.content)
WARNING:root:Some characters could not be decoded, and were replaced with REPLACEMENT CHARACTER.
此警告是由页面声称使用GB2312时使用的GBK码点引起的。
https://stackoverflow.com/questions/23268480
复制相似问题