1、写爬虫代码,报错:
TypeError: cannot use a string pattern on a bytes-like object
出错的主要原因是因为:
TypeError: can’t use a string pattern on a bytes-like object.
html用decode(‘utf-8’)进行解码,由bytes变成string。
py3的urlopen返回的不是string是bytes。
解决办法:https://blog.youkuaiyun.com/tzs_1041218129/article/details/52228905
把’html’类型调整一下:html.decode(‘utf-8’)
参考:https://blog.youkuaiyun.com/jieli_/article/details/70166244
一劳永逸解决:TypeError: cannot use a string pattern on a bytes-like object
import chardet #需要导入这个模块,检测编码格式
encode_type = chardet.detect(html)
html = html.decode(encode_type[‘encoding’]) #进行相应解码,赋给原标识符(变量)
本文详细解析了Python爬虫编程中遇到的TypeError: cannot use a string pattern on a bytes-like object错误,介绍了如何通过正确的解码方式将bytes转换为string,从而避免此问题。文章提供了具体的解决方案,包括使用chardet模块自动检测编码格式,以及如何根据检测结果进行解码。
27万+

被折叠的 条评论
为什么被折叠?



