Python爬虫類のrequestsライブラリ(三):フォームデータとJSONデータを送信します。
2743 ワード
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)