LoginSignup
3
3

More than 3 years have passed since last update.

requestsで日本語(Shift-JIS)に対応したPOSTリクエストをコールしたい場合の方法

Posted at

概要

  • pythonのrequestsモジュールを使ってPOSTメソッドでリクエストをする場合、URLエンコードをするが、日本語のパラメータ値を渡す場合には注意が必要。

  • サイトによってはShift-JIS形式でデコードするものがあり、その場合は、リクエストする側もShift-JIS形式でエンコードしてコールする必要がある

  • requests.postにdict形式で渡すとデフォルトのエンコードが行われるため、urllibモジュールを使いURLエンコードを行いstr型にして直接requestsに渡すことで、デフォルトのエンコードも回避し、Shift-JISでエンコードしたパラメータを渡すことが可能です。

解決法

import requests
import urllib.parse

# postパラメータの値(例)
item = 'ほげ'
post_data = {'KEY1':item}

# shift-jisでエンコードし、str型にする
urlencode_post_data = urllib.parse.urlencode(post_data, encoding='shift-jis')

headers = {'content-type': 'text/html; charset=Shift_JIS'}
response = requests.post(<対象URL>, urlencode_post_data, headers=headers)

終わりに

  • 日本語を扱うと、このような文字コードの問題が出てきます。解決策を検索しても、日本語圏以外のサイトには当てはまる解決法が見つけられず、自力で試行錯誤をして解決しました。少しでもお役に立てればと投稿します。
3
3
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
3
3