`
macken
  • 浏览: 342910 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Python获取html显示乱码

 
阅读更多

 

#!/usr/bin/env python
# -*- coding: GBK -*-
import urllib2
import simplejson

url="http://localhost:82/v1/"
header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.1.14) Gecko/20080404 (FoxPlus) Firefox/2.0.0.14','Accept':'application/json'}
request = urllib2.Request(url, headers=header)
response = urllib2.urlopen(request)
data = response.read()

 在使用以上代码获取html内容时可能会显示乱码,原因可能是由于服务器端返回的数据是utf-8编码,直接显示会出现乱码,解决方法

 

data.decode('utf-8').encode('gb2312')

也可以直接使用

data.decode('utf-8')

  在调用

 

print data

 语句时,系统会自动转换为中文编码输出

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics