python3访问sina首页中文的处理方法

yipeiwu_com6年前Python基础

复制代码 代码如下:

"""
如果只用普通的
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"))

相关文章

python重试装饰器的简单实现方法

简单实现了一个在函数执行出现异常时自动重试的装饰器,支持控制最多重试次数,每次重试间隔,每次重试间隔时间递增。 最新的代码可以访问从github上获取 https://github.co...

Python 通过URL打开图片实例详解

Python 通过URL打开图片实例详解 不论是用OpenCV还是PIL,skimage等库,在之前做图像处理的时候,几乎都是读取本地的图片。最近尝试爬虫爬取图片,在保存之前,我希望能先...

python中plot实现即时数据动态显示方法

python中plot实现即时数据动态显示方法

在Matlab使用Plot函数实现数据动态显示方法总结中介绍了两种实现即时数据动态显示的方法。考虑到使用python的人群日益增多,再加上本人最近想使用python动态显示即时的数据,网...

浅谈Python peewee 使用经验

本文使用案例是基于 python2.7 实现 以下内容均为个人使用 peewee 的经验和遇到的坑,不会涉及过多的基本操作。所以,没有使用过 peewee,可以先阅读文档 正确性和覆盖面...

pow在python中的含义及用法

pow()方法返回xy(x的y次方) 的值 语法 以下是math模块pow()方法的语法: import math math.pow( x, y ) 内置的pow()方法 p...