码迷,mamicode.com
首页 > 编程语言 > 详细

关于Python 中unicode 转码的问题

时间:2014-10-08 14:44:45      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:des   style   http   使用   ar   sp   c   问题   on   

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

关于Python 中unicode 转码的问题

标签:des   style   http   使用   ar   sp   c   问题   on   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!