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

Ins*_*lue 90 python web-crawler python-3.x

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

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)
Run Code Online (Sandbox Code Playgroud)

我得到了这个意想不到的错误:

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
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

roc*_*cky 141

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

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

  • 这解决了错误“TypeError:无法在类似字节的对象上使用字符串模式”,但随后我收到了“UnicodeDecodeError:'utf-8'编解码器无法解码位置1中的字节0xb2:无效起始字节”之类的错误。我通过使用 `.decode("utf-8", "ignore")` 修复了它:/sf/ask/4351943011/ -就位-0/62170725#62170725 (2认同)

Ara*_*Fey 17

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

>>> type(html)
<class 'bytes'>
Run Code Online (Sandbox Code Playgroud)

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

你可以decode将字节串起来:

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

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

regex = rb'<title>(,+?)</title>'
#        ^
Run Code Online (Sandbox Code Playgroud)

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

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

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