标签:ssi head lan encode .text pre header spi requests
兴趣来潮,爬了下51job,但是遇到编码问题!以下是简单的一段代码
获取整个页面数据
# -*- coding:utf-8 -*-
import requests
import sys
reload(sys)
sys.setdefaultencoding(‘utf-8‘)
def spider(url): session = requests.Session() html = session.get(url, headers=headers) return html url = ‘http://www.51job.com/‘ html = spider(url)
结果:
print html.encoding >>>ISO-8859-1
html.text中的某一段
print html.text >>>langs : { ts_qxjzw : ‘???????°??‘ , queren : ‘è·è?‘ , guanbi : ‘1?±?‘ , yxdd : ‘ò???μ?μ?‘ , yxzn : ‘ò????°?ü‘ , yxhy : ‘ò???DDòμ‘ , nzdnxj : ‘?ú×??à?ü????‘ , xiang : ‘??‘ , xjdq : ‘????μ???‘ , xj_xg : ‘????/DT??‘ , zycs : ‘?÷òa3?êD‘ , sysf : ‘?ùóDê?·Y‘ , tspd : ‘ì?êa?μμà‘, qxjgzdd : ‘??????1¤×÷μ?μ?‘ , qxjznlb : ‘???????°?üàà±e‘ , qxjhylb : ‘??????DDòμàà±e‘ , gzdd : ‘1¤×÷μ?μ?‘ , buxian : ‘2??T‘ } ,
我设置html.text.decode(‘ISO-8859-1‘),报错!UnicodeEncodeError: ‘ascii‘ codec can‘t encode characters in position 249-254: ordinal not in range(128)
翻阅了些资料,最终添加了 html.encoding = ‘gbk‘,搞定!
代码:
# -*- coding:utf-8 -*- import requests import sys reload(sys) sys.setdefaultencoding(‘utf-8‘) def spider(url): session = requests.Session() html = session.get(url, headers=headers) html.encoding = ‘gbk‘ return html url = ‘http://www.51job.com/‘ html = spider(url)
展示html中的一段
print html.text >>>langs : { ts_qxjzw : ‘请选择职位‘ , queren : ‘确认‘ , guanbi : ‘关闭‘ , yxdd : ‘已选地点‘ , yxzn : ‘已选职能‘ , yxhy : ‘已选行业‘ , nzdnxj : ‘您最多能选择‘ , xiang : ‘项‘ , xjdq : ‘选择地区‘ , xj_xg : ‘选择/修改‘ , zycs : ‘主要城市‘ , sysf : ‘所有省份‘ , tspd : ‘特殊频道‘, qxjgzdd : ‘请选择工作地点‘ , qxjznlb : ‘请选择职能类别‘ , qxjhylb : ‘请选择行业类别‘ , gzdd : ‘工作地点‘ , buxian : ‘不限‘ } ,
标签:ssi head lan encode .text pre header spi requests
原文地址:http://www.cnblogs.com/dwz1011/p/6284832.html