python3.x - Python3 bytes转str失败?要如何解决?
本文介绍了python3.x - Python3 bytes转str失败?要如何解决?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
我访问的网页明明是bytes代码
In [50]: type(html)
Out[50]: bytes
按照网上的方法,应该是这样转换的str(html,"utf-8")
测试失败!
提示
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
然后又按照教程:html.decode("UTF-8")
测试又失败
提示
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x8b in position 1: invalid start byte
然后也不知道错在哪里?
访问的是百度的源代码,是这样的结果:
不知道有高人指点一下?
解决方案
如果是requests获取的话,
可以尝试
req = requests.get(url)
req.encoding = "utf-8"
或者
req.encoding = req.apparent_encoding
这篇关于python3.x - Python3 bytes转str失败?要如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文