LoginSignup
0
0

More than 1 year has passed since last update.

Python RequestsモジュールでのJSONDecodeError

Last updated at Posted at 2021-09-28

概要

  • PythonのRequestsモジュールを利用して、APIレスポンスを取得しようとしたがJSONDecodeErrorになり、うまく取得できなかった。
  • レスポンスがHTMLなのにJSONに変換しようとしていたことが原因。
  • とりあえず、Unicodeに変換したらちゃんと取得できた。

もうちょっと詳しく

エラーが出た。。。なぜ?

以下のようにrequests.requestでResponseを取得してr.json()でJSONに変換した。

r = requests.request(method, URL, heasers=headre, data=data)
return r.json()

そうすると下記のエラーが出た。。。
JSONDecodeError, Expecting value: line 1 column 1 (char 0)

色々試したところ、requests.requestで取得したResponseオブジェクトrがHTMLだということがわかった。

対処!!
requests.requestで取得したrequests.ResponseオブジェクトをUnicodeに変換。

r = requests.request(method, URL, heasers=headre, data=data)
return r.text()

これでとりあえずHTMLを取得できた。

Beautiul Soupを利用すると、さらにHTMLからうまいことデータを抽出できるらしい。試していませんが、興味ある方は参考に載せたサイトをどうぞ。

参考

  • Requetsモジュール仕様

  • Beautiul Soupについて

0
0
0

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
0
0