https://blog.youkuaiyun.com/J__Max/article/details/82937774
解决方法是:把’html’类型调整一下:html.decode(‘utf-8’)
、
from urllib import request as rr
import re
url = 'http://www.baidu.com'
content = rr.urlopen(url).read()
title = re.findall(r"<title>(.*?)</title>", content)
print(title)
执行上面的代码时,控制台会报错,错误如下:
File "/Users/jiangnan/Desktop/Data_Collecting/venv/lib/python3.6/re.py", line 222, in findall
return _compile(pattern, flags).findall(string)
TypeError: cannot use a string pattern on a bytes-like object
出错的原因如下:
urlopen返回的是bytes类型,而在使用re.findall()模块时,要求的是string类型
解决办法:
通过content.decode(‘utf-8’),将content的类型转换为string
正确执行的代码如下:
from urllib import request as rr
import re
url = 'http://www.baidu.com'
content = rr.urlopen(url).read()
title = re.findall(r"<title>(.*?)</title>", content.decode('utf-8'))
博客主要围绕Python代码报错展开。执行代码时,因urlopen返回bytes类型,而re.findall()模块要求string类型,导致报错。解决办法是通过content.decode('utf-8')将content类型转换为string,并给出了正确执行的代码示例。
696

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



