https://blog.csdn.net/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'))