TypeError:不能在 re.findall() 中的类字节对象上使用字符串模式

新手上路,请多包涵

我正在尝试学习如何从页面自动获取 url。在下面的代码中,我试图获取网页的标题:

 import urllib.request
import re

url = "http://www.google.com"
regex = r'<title>(,+?)</title>'
pattern  = re.compile(regex)

with urllib.request.urlopen(url) as response:
   html = response.read()

title = re.findall(pattern, html)
print(title)

我得到了这个意外错误:

 Traceback (most recent call last):
  File "path\to\file\Crawler.py", line 11, in <module>
    title = re.findall(pattern, html)
  File "C:\Python33\lib\re.py", line 201, in findall
    return _compile(pattern, flags).findall(string)
TypeError: can't use a string pattern on a bytes-like object

我究竟做错了什么?

原文由 Inspired_Blue 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 709
2 个回答

您想使用 .decode 将 html(类似字节的对象)转换为字符串,例如 html = response.read().decode('utf-8')

请参阅 将字节转换为 Python 字符串

原文由 rocky 发布,翻译遵循 CC BY-SA 3.0 许可协议

问题是你的正则表达式是一个字符串,但是 html字节

 >>> type(html)
<class 'bytes'>

由于 python 不知道这些字节是如何编码的,因此当您尝试对它们使用字符串正则表达式时它会抛出异常。

您可以将 decode 字节转换为字符串:

 html = html.decode('ISO-8859-1')  # encoding may vary!
title = re.findall(pattern, html)  # no more error

或者使用字节正则表达式:

 regex = rb'<title>(,+?)</title>'
#        ^


在此特定上下文中,您可以从响应标头中获取编码:

 with urllib.request.urlopen(url) as response:
    encoding = response.info().get_param('charset', 'utf8')
    html = response.read().decode(encoding)

有关详细信息,请参阅 urlopen 文档

原文由 Aran-Fey 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题