TypeError: re.findall() 内のバイト系オブジェクトに文字列パターンは使用できません 質問する

TypeError: re.findall() 内のバイト系オブジェクトに文字列パターンは使用できません 質問する

ページから URL を自動的に取得する方法を学習しようとしています。次のコードでは、Web ページのタイトルを取得しようとしています。

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

何が間違っているのでしょうか?

ベストアンサー1

.decodeたとえば、を使用して html (バイトのようなオブジェクト) を文字列に変換したいとしますhtml = response.read().decode('utf-8')

見るバイトをPython文字列に変換する

おすすめ記事