您的位置:首页 > 编程语言 > Python开发

关于Python 中unicode 转码的问题

2014-10-08 13:40 232 查看
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 进行赋值
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: