Python 中urllib2.urlopen 中存在中文转码问题,解决方法如下:

1.

import BeautifulSoup
import chardet

response =urllib2.urlopen('%s'%line)
#response.decode('utf-8')
#response = urllib2.urlopen('http://www.baidu.com/')
html = response.read()
pdb.set_trace()
#print html.decode('big5').encode('utf8')
urlcodestyle=chardet.detect(html)
sourcehtml=html.decode('%s'%urlcodestyle['encoding']).encode('utf-8')

2.sourcehtml 的使用方法:

import BeautifulSoup
"""
if 'encoding' in urlcodestyle:
soup=BeautifulSoup(html,fromEncoding="%s"%urlcodestyle['encoding'])
else :
soup=BeautifulSoup(html,fromEncoding="gb18030")
"""

最好能够通过获得请求页面的编码格式,然后再对fromEncoding 进行赋值

posted on 2014-10-08 13:40  yuyezhulan  阅读(671)  评论(0编辑  收藏  举报