文字化けの原因
res.content をBeutifulSoupがエンコードをするときに使ったのが'windows-1252'
だから文字化けした
'windows-1252'
を使うことになったのは﨏
という機種依存文字?
文字化けしないURLで使われたエンコードは'euc-jp'
だった
以下、詳細
mojibake.py
# 文字化けしたURL
url = "https://db.netkeiba.com/race/202204010808/"
res = requests.get(url)
soup = BeautifulSoup(res.content, "html.parser")
soup.original_encoding
# 'windows-1252'
soup.select("h1")[1].text
# '4ºÐ°Ê¾å1¾¡¥¯¥é¥¹'
# 文字化けしないURL
url = "https://db.netkeiba.com/race/202204010807/"
res = requests.get(url)
soup = BeautifulSoup(res.content, "html.parser")
soup.original_encoding
# 'euc-jp'
soup.select("h1")[1].text
# '4歳以上1勝クラス'
# 文字化けしないURLでもエンコードを'windows-1252'にすると文字化けする
url = "https://db.netkeiba.com/race/202204010807/"
res = requests.get(url)
soup = BeautifulSoup(res.content, "html.parser", from_encoding="windows-1252")
soup.original_encoding
# 'windows-1252'
soup.select("h1")[1].text
# '4ºÐ°Ê¾å1¾¡¥¯¥é¥¹'
対応策
公式ドキュメントから:
If one parser isn’t working on a certain document, the best solution is to try a different parser.
あるパーサーが特定の文書で機能しない場合、最良の解決策は別のパーサーを試すことです。
なので、①は以下のようにすると文字化けせずに取得できます
soup = BeautifulSoup(res.content, "lxml")
# or
soup = BeautifulSoup(res.content, "html5lib")
であれば、なぜパーサーを変えただけで文字化けしないのか?
BeutifulSoup __init__.py
の Docstring に
It works better if lxml and/or html5lib is installed.
lxmlやhtml5libがインストールされているとより効果的です。
と書いてあるからそういうものなんだろう。(1から10まで読んでないので曖昧)
上記の方法でも文字化けするようなら
②の手法を使えば、ほぼ文字化けするサイトは無いと思います