【问题标题】:TypeError: can't use a string pattern on a bytes-like object in re.findall()TypeError:不能在 re.findall() 中的类似字节的对象上使用字符串模式
【发布时间】:2015-09-10 06:14:23
【问题描述】:

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

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

我做错了什么?

【问题讨论】:

标签: python python-3.x web-crawler


【解决方案1】:

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

Convert bytes to a Python String

【讨论】:

  • 这解决了错误TypeError: cannot use a string pattern on a bytes-like object,但后来我得到了UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb2 in position 1: invalid start byte之类的错误。我使用.decode("utf-8", "ignore") 修复了它:stackoverflow.com/questions/62170614/…
  • "ignore" 忽略。如果这是你想要的,那么一切都很好。然而,有时这种问题掩盖了更深层次的问题,例如你想要解码的东西真的是不可解码的或本来就是不可解码的,例如压缩或加密的文本。或者它可能需要一些其他编码,例如 utf-16 。警告购买者。
【解决方案2】:

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

>>> 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 documentation

【讨论】:

    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多