老猿前期执行如下代码时报“‘utf-8’ codec can’t decode byte”错,代码及错误信息如下:

>>> import urllib.request
>>> def mkhead():
header = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Encoding':'gzip',
'Accept-Language':'zh-CN,zh;q=0.9',
'Connection':'keep-alive',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} return header >>> def readweb(site):
header = mkhead()
try:
req = urllib.request.Request(url=site,headers=header)
text = urllib.request.urlopen(req).read().decode()
except Exception as e:
print(e)
return None
else:return text >>> readweb(r'https://blog.csdn.net/LaoYuanPython')
'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
>>>

才开始以为是decode编码的问题,试了gbk等方式还是不行,最后发现是因为http请求报文头“‘Accept-Encoding’:‘gzip’”导致服务器返回的报文压缩了,把这个报文头信息去掉再执行就ok了,如下:

>>> import urllib.request
>>> def mkhead():
header = {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Accept-Language':'zh-CN,zh;q=0.9',
'Connection':'keep-alive',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36'} return header >>> def readweb(site):
header = mkhead()
try:
req = urllib.request.Request(url=site,headers=header)
text = urllib.request.urlopen(req).read().decode()
except Exception as e:
print(e)
return None
else:return text >>> readweb(r'https://blog.csdn.net/LaoYuanPython')
Squeezed text(273 lines)
>>> readweb(r'https://blog.csdn.net/LaoYuanPython')[0:100]
'<!DOCTYPE html>\n<html lang="zh-CN">\n<head>\n <meta charset="UTF-8">\n <link rel="canonical" href'
>>>

如果希望处理压缩报文,请参考《第14.7节 Python模拟浏览器访问实现http报文体压缩传输》。

老猿Python,跟老猿学Python!

博客地址:https://blog.csdn.net/LaoYuanPython


老猿Python博客文章目录:https://blog.csdn.net/LaoYuanPython/article/details/98245036

请大家多多支持,点赞、评论和加关注!谢谢!

urllib.request.urlopen(req).read().decode解析http报文报“utf-8 codec can not decode”错处理的更多相关文章

  1. (转)python3 urllib.request.urlopen() 错误UnicodeEncodeError: 'ascii' codec can't encode characters

    代码内容: url = 'https://movie.douban.com/j/search_subjects?type=movie'+ str(tag) + '&sort=recommend ...

  2. python之urllib.request.urlopen(url)报错urllib.error.HTTPError: HTTP Error 403: Forbidden处理及引申浏览器User Agent处理

    最近在跟着院内大神学习python的过程中,发现使用urllib.request.urlopen(url)请求服务器是报错: 在园子里找原因,发现原因为: 只会收到一个单纯的对于该页面访问的请求,但是 ...

  3. python 3以上版本使用pickle.load读取文件报UnicodeDecodeError: 'ascii' codec can't decode byte 0x8b in position 6

    python 3以上版本使用pickle.load读取文件报UnicodeDecodeError: 'ascii' codec can't decode byte 0x8b in position 6 ...

  4. python3 urllib.request.urlopen() 地址打开错误

    错误内容:UnicodeEncodeError: 'ascii' codec can't encode characters in position 28-29: ordinal not in ran ...

  5. pycharm debug调试模式报“UnicodeDecodeError:'gdk' codec can't decode byte 0xac”,无法正常调试

    遇到的问题: 本机python 3.8 pycharn 3.4.4 运行代码的时候,选择debug模式,提示"UnicodeDecodeError:'gdk' codec can't dec ...

  6. python-使用pip安装第三方库报UnicodeDecodeError: 'utf8' codec can't decode byte 0xcb in position 7: invalid continuation byte 错误解决方案

    在python 的安装目录下找到Lib\ntpath.py文件,找到def join(path, *paths):方法,添加如下两行语句: reload(sys) sys.setdefaultenco ...

  7. Windows下面安装easy_install报UnicodeDecodeError: 'ascii' codec can't decode byte解决方法

    在运行python ez_setup.py install后, 发现是在下载并解压setuptools-2.1,并运行setup.py时出现如下错误: 提示D:\Python27\lib\mimety ...

  8. pip 安装pandas报UnicodeDecodeError: 'ascii' codec can't decode byte 0xd5错

    当Python在window环境中通过pip安装pandas报标题这样的错,主要是因为python默认编码格式是:ascii 在https://www.python.org/dev/peps/pep- ...

  9. 爬虫之urllib.request基础使用(一)

    urllib模块 urllib模块简介: urllib提供了一系列用于操作URL的功能.包含urllib.request,urllib.error,urllib.parse,urllib.robotp ...

随机推荐

  1. ashx接收前台传来的数据

    前台js: $(function () { $.ajax({ url: "/TestAshx/GetJson.ashx", type: "post", data ...

  2. 记一次使用idea插件CamelCase技巧

    1.在idea中下载插件CamelCase插件  2.使用Shift+Alt+U快捷键进行转换 3.由于转换格式比较导致多次使用快捷键才能达到自己想要的效果,此插件提供了允许禁用某些转换或更改它们在首 ...

  3. html的height:100%;高度是多少

    html的height:100%;高度是多少 html设置height:100%;表示一屏高度,类似于100vh.未设置则根据子元素的高度来自适应高.在实际应用中,设置页面高度为1屏幕高度通常设置: ...

  4. 从头学起Verilog(一):组合逻辑基础与回顾

    引言 该部分主要回顾了本科时数字电路中组合逻辑电路部分,内容相对简单和基础. 内容主要包括:布尔代数相关知识,卡诺图,最大项与最小项,竞争和冒险以及一些常见模块 数字电路中的逻辑 组合逻辑:输出可以表 ...

  5. 03 原型模式(prototype)

    03 原型模式(prototype) 1 克隆羊问题 现在有一只羊tom,姓名为: tom.年龄为: 1,颜色为:白色,请编写程序创建和tom羊属性完全相同的10只羊. 2 传统方式解决 思路 cla ...

  6. CCF-201512-消除类游戏

    问题描述 试题编号: 201512-2 试题名称: 消除类游戏 时间限制: 1.0s 内存限制: 256.0MB 问题描述: 问题描述 消除类游戏是深受大众欢迎的一种游戏,游戏在一个包含有n行m列的游 ...

  7. sync_with_stdio(false)和cin.tie(NULL)

    std::ios::sync_with_stdio(false) 这个函数相当于是否兼容stdio的开关,默认为true C++为了兼容C,保证程序在使用了std::printf和std::cout的 ...

  8. 01、MyBatis HelloWorld

    1. MyBatis简介 1)MyBatis 是支持定制化 SQL.存储过程以及高级映射的优秀的持久层框架 2)MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集 3)MyB ...

  9. Android10_原理机制系列_AMS(ATMS)之应用的第一次启动的过程

    概述 该篇基于Android 10的代码.在 AMS之AMS的启动---Android Framework(Android 10) 中已经介绍了,在Android 10中,activity的调度和管理 ...

  10. Python 调用Get接口

    import requests,jsonurl = 'http://localhost:30627/api/jobs/GetNuberId?id=2'req = requests.get(url)re ...