关于Python 中unicode 转码的问题

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 进行赋值

原文地址:https://www.cnblogs.com/yuyezhulan/p/4010988.html