13.pythonのrequests
◼︎requests
urllibよりもrequestsの方が使いやすい
人が使いやすいように設計されていて、Pythonで書かれている Apache2 Licensed ベースのHTTPライブラリです。
◼︎python
import requests
from requests import Response
# timeoutを付けることでtimeout時間以内にレスポンスが無いとエラーとすることができる
payload: dict = {'key1': 'value1', 'key2': 'value2'}
r: Response = requests.get('http://httpbin.org/get'
, params=payload
, timeout=1)
# 200
print(r.status_code)
'''
{
"args": {
"key1": "value1",
"key2": "value2"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Connection": "close",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.19.1"
},
"origin": "121.233.112.18",
"url": "http://httpbin.org/get?key1=value1&key2=value2"
}
'''
print(r.text)
{
'args': {'key1': 'value1', 'key2': 'value2'},
'headers': {
'Accept': '*/*',
'Accept-Encoding': 'gzip, deflate',
'Connection': 'close',
'Host': 'httpbin.org',
'User-Agent': 'python-requests/2.19.1'},
'origin': '121.233.112.18',
'url': 'http://httpbin.org/get?key1=value1&key2=value2'
}
print(r.json())
# 118.241.128.98
print(r.json()['origin'])
# http://httpbin.org/get?key1=value1&key2=value2
print(r.json()['url'])
◼︎Get以外の書き方
# post
r = requests.post('http://httpbin.org/post', params=payload)
# put
r = requests.put('http://httpbin.org/put', params=payload)
# delete
r = requests.delete('http://httpbin.org/delete', params=payload)
この記事が気に入ったらサポートをしてみませんか?