python3访问sina首页中文的处理方法
2014-02-24 00:00
661 查看
""" 如果只用普通的 import urllib.request html = urllib.request.urlopen("http://www.sina.com").read() print(html.decode('gbk')) 出现下面的错误 builtins.UnicodeDecodeError: 'gbk' codec can't decode byte 0x8b in position 1: illegal multibyte sequence 怎么办?原来是有的网站将网页用gzip压缩了 。 请看下面的代码 建议大家用python2 import urllib2 from StringIO import StringIO import gzip request = urllib2.Request('http://www.sina.com') request.add_header('Accept-encoding', 'gzip') response = urllib2.urlopen(request) if response.info().get('Content-Encoding') == 'gzip': buf = StringIO( response.read()) f = gzip.GzipFile(fileobj=buf) data = f.read() print data.decode("GBK").encode('utf-8') """ import io import urllib.request as r import gzip req = r.Request("http://www.sina.com", headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36", "Accept-Encoding": "gzip"}) bs = r.urlopen(req).read() bi = io.BytesIO(bs) gf = gzip.GzipFile(fileobj=bi, mode="rb") print(gf.read().decode("gbk"))
相关文章推荐
- python3访问sina首页中文的处理方法
- python3访问sina首页中文的处理方法
- Python2中文处理纪要的实现方法
- python中文处理好方法
- Python中文路径及"ValueError: invalid \x escape"的处理方法
- easyUI icon中文命名图片无法在浏览器中访问处理方法
- python 字典中文key处理,读取,比较方法
- Python处理中文文本字符时提取某个汉字或字符的方法
- python中读写文件及中文编码处理方法
- Python 2.7中文显示与处理方法
- python 处理中文时出现的错误'ascii' codec can't decode byte 0xe9 in position 0: ordinal not in range(128)" 解决方法
- python3处理含有中文的url方法
- NodeJs服务器启动后在浏览器访问时中文显示乱码处理方法
- Python零基础入门二十五之访问互联网异常的处理方法
- gzip 压缩格式的网站处理方法---sina.com 分类: python python基础学习 2013-07-16 17:40 362人阅读 评论(0) 收藏
- python处理csv文件名中中文字符解决方法
- Python中文路径及"ValueError: invalid \x escape"的处理方法
- python中读写文件及中文编码处理方法【整理】
- python中读写文件及中文编码处理方法
- Python点滴02_Python3打开中文文本时报错的一种处理方法