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获取统计自己的qq群成员信息的方法

Python获取统计自己的qq群成员信息的方法

首先说明一下需要使用的工具以及技术:python3 + selenium selenium安装方法:pip install selenium 前提:获取自己的qq群成员信息,自己必须是群...

详解Python logging调用Logger.info方法的处理过程

详解Python logging调用Logger.info方法的处理过程

本次分析一下Logger.info的流程 1. Logger.info源码: def info(self, msg, *args, **kwargs): """ Log...

python中模块查找的原理与方法详解

前言 本文主要给大家介绍了关于python模块查找的原理与方式,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 基础概念 module 模块, 一个 py 文件或以其他文...

Python常用字符串替换函数strip、replace及sub用法示例

本文实例讲述了Python常用字符串替换函数strip、replace及sub用法。分享给大家供大家参考,具体如下: 今天在做一道今年秋季招聘题目的时候遇上了一个替换的问题,题目看起来好...

python统计指定目录内文件的代码行数

python统计指定目录内文件的代码行数

python统计指定目录内文件的代码行数,程序实现统计指定目录内各个python文件的代码总行数,注释行数,空行数,并算出所占百分比 这符合一些公司的小需求,实际代码量的统计工作 效果如...