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

yipeiwu_com5年前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基于pygame实现图片代替鼠标移动效果

Python基于pygame实现图片代替鼠标移动效果

本文实例讲述了Python基于pygame实现图片代替鼠标移动效果。分享给大家供大家参考,具体如下: 想想现在学校pygame有几个钟了,就写了一个小程序:图片代替鼠标移动 程序的运行效...

Python多线程编程(四):使用Lock互斥锁

前面已经演示了Python:使用threading模块实现多线程编程二两种方式起线程和Python:使用threading模块实现多线程编程三threading.Thread类的重要函数...

Python微信库:itchat的用法详解

Python微信库:itchat的用法详解

在论坛上看到了用Python登录微信并实现自动签到,才了解到一个新的Python库: itchat 库文档说明链接在这:  itchat 我存个档在我网站(主要是我打...

在Django中创建动态视图的教程

在我们的`` current_datetime`` 视图范例中,尽管内容是动态的,但是URL ( /time/ )是静态的。 在 大多数动态web应用程序,URL通常都包含有相关的参数。...

Python列表对象实现原理详解

Python列表对象实现原理详解

Python中的列表基于PyListObject实现,列表支持元素的插入、删除、更新操作,因此PyListObject是一个变长对象(列表的长度随着元素的增加和删除而变长和变短),同时它...