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

Python3 使用urllib库模拟请求头的错误。

代码:

import urllib.request

url = 'http://www.baidu.com'
# 模拟请求头
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36"
}
# 设置一个请求体
req = urllib.request.Request(url, headers=headers)

# 发起请求
response = urllib.request.urlopen(req)
html = response.read().decode('utf-8')
print(html)

注意代码中的模拟请求头的信息时在浏览器中赋值而来,方法是在浏览器器中按F12》NetWork》F5刷新》在Name中找到baidu.com》找到headers》找到User-Agent

python3 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte_第1张图片

找到如下图所示内容:

找到User-Agent

运行如上所示的代码,程序会报错。

    html = response.read().decode('utf-8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte

解决方案:

更改headers字典中"User-Agent"的拼写,改成"User-Agnet"。

python3 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte_第2张图片

你可能感兴趣的:(编程技巧,Python)