8/24 UnicodeDecodeErrorその2
Pythonクロ&スクp49
htmlを開いて中身を変数htmlに保存しようとしたところ, read()の箇所で,
UnicodeDecodeError: 'cp932' codec can't decode byte 0x8d in position 147: illegal multibyte sequence
が出たので, open()のエンコーディングを指定したところうまくいった.
import re from html import unescape with open("dp.html", encoding='utf-8') as f: #"encoding='utf-8'"を追加 html = f.read() for partial_html in re.findall(r'<a itemprop="url".*?</ul>\s*</a></li>', html, re.DOTALL): url = re.search(r'<a itemprop="url" href="(.*?)">', partial_html).group(1) url = 'https://gihyo.jp' + url title = re.search(r'<p itemprop="name".*?</p>', partial_html).group(0) title = title.replace('<br/>', '') title = re.sub(r'<.*?>', '', title) title = unescape(title) print(url, title)