手机
当前位置:查字典教程网 >脚本专栏 >python >python3访问sina首页中文的处理方法
python3访问sina首页中文的处理方法
摘要:复制代码代码如下:"""如果只用普通的importurllib.requesthtml=urllib.request.urlopen("ht...

复制代码 代码如下:

"""

如果只用普通的

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首页中文的处理方法】相关文章:

Python获取当前时间的方法

python list 合并连接字符串的方法

python的正则表达式re模块的常用方法

python中文乱码的解决方法

rhythmbox中文名乱码问题解决方法

Python中删除文件的程序代码

Python列表推导式的使用方法

python 获取本机ip地址的两个方法

python paramiko实现ssh远程访问的方法

下载给定网页上图片的方法

精品推荐
分类导航