老猿前期执行如下代码时报“‘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. Inception系列之Inception_v1

    目前,神经网络模型为了得到更好的效果,越来越深和越来越宽的模型被提出.然而这样会带来以下几个问题: 1)参数量,计算量越来越大,在有限内存和算力的设备上,其应用也就越难以落地. 2)对于一些数据集较少 ...

  2. unix进程间通信方式(IPC)

    unix进程间通信方式(IPC) 管道(Pipe):管道可用于具有亲缘关系进程间的通信,允许一个进程和另一个与它有共同祖先的进程之间进行通信. 命名管道(named pipe):命名管道克服了管道没有 ...

  3. Pycharm激活码,2020年9月29日最新激活码

    分享一个Pycharm激活码给大家: 5MJ8MJ2T1Q-eyJsaWNlbnNlSWQiOiI1TUo4TUoyVDFRIiwibGljZW5zZWVOYW1lIjoi6I635Y+W77yaIG ...

  4. C# 9.0 正式发布了(C# 9.0 on the record)

    翻译自 Mads Torgersen 2020年11月10日的博文<C# 9.0 on the record> [1],Mads Torgersen 是微软 C# 语言的首席设计师,也是微 ...

  5. Numpy_01

    # 引子: # ndarray 是一个 numpy库提供的 同构数据多维模型 import numpy as np list=[1,2,3,4,5,6] myndarray=np.array(list ...

  6. Jar 和 war 区别

    jar包:对于学习java的人来说应该并不陌生.我们也经常使用也一些jar包.其实jar包就是java的类进行编译生成的class文件就行打包的压缩包而已.里面就是一些class文件.当我们自己使用m ...

  7. 一篇文章了解_unittest

    1. 基本概念 2018年10月7日 星期日 11:39 unittest是python自带的单元测试框架,有时候又被称为"PyUnit",是python版本的JUint实现. 该 ...

  8. springMVC中添加<mvc:resource>时的问题

    为了解决SpringMVC在使用<url-pattern>/</url-pattern>时会屏蔽掉所有静态资源的问题 在springMVC.xml 配置文件中加入了如下代码: ...

  9. webug第十四关:存储型XSS

    第十四关:存储型XSS 打开发现是评论区 留言加入xss语句

  10. 攻克solo第七课(Randy Rhoads风格)

    本期文章,笔者将通过Guitar Pro 7吉他软件跟大家分享一下Randy Rhoads的solo句子. 相信很多精研电吉他的朋友都会听过这个一手把Ozzy Osbourne从离开黑色安息日乐队的深 ...