zz775520666 发表于 2017-4-27 09:52:54

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
  
 语句时,系统会自动转换为中文编码输出
页: [1]
查看完整版本: Python获取html显示乱码