HTML を拾ってきて正規表現で処理しようと以下のようなコードを書いたら
#!/usr/bin/env python3 import urllib.request import re url = 'https://example.com/' with urllib.request.urlopen(url) as response: html = response.read() m = re.search(r'(?s)<body>(.*)</body>', html)以下のようなエラーが出た。
$ ./hoge.py Traceback (most recent call last): File "./hoge.py", line 8, in <module> m = re.search(r'(?s)<body>(.*)</body>', html) File "/usr/lib/python3.8/re.py", line 201, in search return _compile(pattern, flags).search(string) TypeError: cannot use a string pattern on a bytes-like object
「cannot use a string pattern on a bytes-like object python regex」でググると以下のページを見つけた。
以下のようにして UTF-8 に直せとのこと
- stackoverflow / 2015-06-21: TypeError: can't use a string pattern on a bytes-like object in re.findall()
以下のようにして UTF-8 に直せとのこと
html = response.read().decode('utf-8')
タグ
コメントをかく