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)
8/18 UnicodeEncodeError
Pythonクロ&スクp45
エンコーディングを取得してutf-8にデコードしたものをhtmlファイルに保存しようとしたら,
UnicodeEncodeError: 'cp932' codec can't encode character '\xa9' in position 37940: illegal multibyte sequence
とprint()の箇所でエラーを吐出したので, デコードを実行するファイルの中身を,
import sys import urllib.request import io #add req = urllib.request.Request("https://gihyo.jp/dp", headers={"User-Agent": "Mozilla/5.0"}) res = urllib.request.urlopen(req) encoding = res.info().get_content_charset(failobj="utf-8") print('encoding:', encoding, file=sys.stderr) text = res.read().decode(encoding) sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') #add print(text)
として, #addとコメントアウトした行を加えたところエラーが消えた.
ioモジュールについては全くの無知なので要勉強.
(追記)
後日#addを抜いたコードを実行したらうまくいった.
なぜだ...
8/17 urllibによるWebページの取得
Pythonクロ&スク p43
urllibを使ってWebページを取得しようとしたら, アクセス拒否をされて403が出た.
対処はUser-Agentを偽造することでアクセスできた.
>>> import urllib.request >>> >>> request = urllib.request.Request("https://gihyo.jp/dp", headers={"User-Agent": "Mozilla/5.0"}) >>> response = urllib.request.urlopen(request)