LoginSignup
108
53

More than 5 years have passed since last update.

Requestsで日本語を扱うときの文字化けを直す

Last updated at Posted at 2016-10-10

環境

Python: 3.5
Requests: 2.11.1

概要

Requestsを使って日本語ページを取得したときに表示すると文字化けが起こる。
今回、自分の場合はページ側のエンコードがShift-JISの場合に起こっていた。

import requests

response = requests.get('適当な日本語ページ')
print(response.encoding)

で調べると、ISO-8859-1が返ってきていた。
どうも、文字コードがうまく取れてない場合に適当にかえしてる??

解決

import requests

response = requests.get('適当な日本語ページ')
response.encoding = response.apparent_encoding  # この行を追加

apparent_encodingを呼び出すと、どうやらライブラリ使って、ちゃんと文字コードを判定するらしい。
今回の場合は、これで文字化けしなくなった。

参考

108
53
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
108
53