python3 获取百度首页源码

最近在学习python3爬虫,爬取百度首页的时候遇到了一些问题,说是解码错误,网上找了一些也是一样的写法,下面是我的方法

python环境为:python3.6..5

import urllib.request

response = urllib.request.urlopen('http://www.baidu.com')

print(response.read().decode('utf8'))

下面是错误内容

---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-2-549c9418a074> in <module>()
      7 #buff = BytesIO(response.read()) # 把content转为文件对象
      8 #f = gzip.GzipFile(fileobj=buff)
----> 9 print(response.read().decode('utf8'))

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

说是解码错误

网址换成http://www.taobao.com此时没有问题

回到获取百度首页的代码,查看一下网页的信息

print(response.info())

下面是输出内容

Content-Type: text/html
Content-Encoding: gzip
Content-Length: 8394
Cache-Control: no-store
Pragma: no-cache
Expires: -1
Connection: close

实际上是百度网页压缩成gzip了,解压缩就可以了

import urllib.request
from io import BytesIO
import gzipresponse = urllib.request.urlopen('http://www.baidu.com')
buff = BytesIO(response.read())      # 把content转为文件对象
f = gzip.GzipFile(fileobj=buff)
print(f.read().decode('utf8'))

这次就好了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值