老猿前期执行如下代码时报“‘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. pytest框架执行自动化测试时使用pycharm正常运行,使用cmd或Terminal报错:Hint: make sure your test modules/packages have valid Python names.

    问题描述: 使用pytest框架做接口自动化测试时,在测试用例所在的.py文件下使用pycharm的run功能可以正常跑用例,使用cmd运行窗口或Terminal则报下图中的错误: Hint: mak ...

  2. C的输入&输出

    格式说明符 输出 %d整型输出,%ld长整型输出, %o以八进制数形式输出整数, %x以十六进制数形式输出整数,或输出字符串的地址. %u以十进制数输出unsigned型数据(无符号数).注意:%d与 ...

  3. ORA-00020: maximum number of processes (40) exceeded模拟会话连接数满

    问题描述:在正式生产环境中,有的库建的process和session连接数目设置的较小,导致后期满了无法连接.因为正式库无法进行停库修改,只能释放连接,做个测试模拟 1. 修改现有最大会话与进程连接数 ...

  4. Mac环境MySql初始密码设置

    1. 首先 点击系统偏好设置 -> 点击MySQL, 在弹出的页面中,关闭服务.2. 进入终端命令输出: cd /usr/local/mysql/bin/ 命令,回车.3. 回车后,输入命令:s ...

  5. Js中函数声明和函数表达式的区别

    先看以下几段烧脑的代码: f();//=>? var f = function () { console.log("var"); } function f() { conso ...

  6. 主动关闭 tcp fin-wait-2 time-wait 定时器

    后面整理相关信息 //后面整理相关信息 /* * This function implements the receiving procedure of RFC 793 for * all state ...

  7. 手把手教你5分钟从零开发一款简易的IDEA插件!项目经验/毕设不愁了!

    我这个人没事就喜欢推荐一些好用的 IDEA 插件给大家.这些插件极大程度上提高了我们的生产效率以及编码舒适度. 不知道大家有没有想过自己开发一款 IDEA 插件呢? 我自己想过,但是没去尝试过.刚好有 ...

  8. Go原生和GoFrame的Cookie关于MaxAge区别

    Go原生和GoFrame的Cookie关于MaxAge区别 环境: gf v1.14.4 go 1.11 Go原生 type Cookie struct { Name string Value str ...

  9. webug第七关:越权

    第七关:越权 观察url 将name换成admin 更改了admin的密码

  10. c#多播委托判断空值

    int resualt = (int)fn?.Invoke(a, b); 其中fn是有两个参数一个int返回值的多播委托,这个看起来很精炼,大概意思也不懂 个人理解为使用先判断fn?,再传值以及输出为 ...