return _compile(pattern, flags).findall(string) TypeError: cannot use a string pattern on a bytes-li

return _compile(pattern, flags).findall(string) TypeError: cannot use a string pattern on a bytes-like object

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'))

print(title)

猜你喜欢

转载自blog.csdn.net/J__Max/article/details/82937774
今日推荐