フォームデータとJSONデータをPython爬虫類庫requestsを使って送信します。


Python爬虫類庫Requestsを導入します。

import requests
一、フォームデータの送信
フォームデータを送信するには、一つの辞書をパラメータdataに渡す必要があります。

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)

{"args":{},"data":"","files":{},"form":{"key1":"value1","key2":"value2"},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.14.2"},"json":null,"origin":"110.18.198.88","url":"http://httpbin.org/post"}
1つのタプルリストをパラメータdataに渡すこともでき、複数のvalueが1つのkeyに対応することができる(辞書のkeyは一意でなければならない)。

payload = (('key1', 'value1'), ('key1', 'value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)

{"args":{},"data":"","files":{},"form":{"key1":["value1","value2"]},"headers":{"Accept":"*/*","Accept-Encoding":"gzip, deflate","Connection":"close","Content-Length":"23","Content-Type":"application/x-www-form-urlencoded","Host":"httpbin.org","User-Agent":"python-requests/2.14.2"},"json":null,"origin":"110.18.198.88","url":"http://httpbin.org/post"}
二、文字列(JSON)データの送信
json文字列をパラメータdataに渡す

import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
辞書をパラメータjsonに渡す

url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url,json=payload)
Python爬虫類庫requestsの使い方については、下記の関連リンクをご覧ください。