Requests-working-with-requests

提供:Dev Guides
移動先:案内検索

リクエスト-リクエストの操作

この章では、リクエストモジュールの操作方法を理解します。 私たちは以下を調べます-

  • HTTPリクエストを行う。
  • パラメータをHTTPリクエストに渡す。

HTTPリクエストを行う

Httpリクエストを行うには、まず以下に示すようにリクエストモジュールをインポートする必要があります-

import requests

次に、requestsモジュールを使用してURLを呼び出す方法を見てみましょう。

コードでURL − [[1]]

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.status_code)

URL-https://jsonplaceholder.typicode.com/usersは、requests.get()メソッドを使用して呼び出されます。 URLの応答オブジェクトはgetdata変数に格納されます。 変数を出力すると、200応答コードが返されます。これは、応答が正常に取得されたことを意味します。

出力

E:\prequests>python makeRequest.py
<Response [200]>

応答からコンテンツを取得するには、次のように getdata.content を使用して取得できます-

import requests
getdata = requests.get('https://jsonplaceholder.typicode.com/users')
print(getdata.content)

getdata.contentは、応答で利用可能なすべてのデータを出力します。

出力

E:\prequests>python makeRequest.py
b'[\n {\n  "id": 1,\n  "name": "Leanne Graham",\n  "username": "Bret",\n
"email": "[email protected]",\n  "address": {\n  "street": "Kulas Light
",\n  "suite": "Apt. 556",\n  "city": "Gwenborough",\n  "zipcode": "
92998-3874",\n  "geo": {\n "lat": "-37.3159",\n  "lng": "81.149
6"\n }\n },\n  "phone": "1-770-736-8031 x56442",\n  "website": "hild
egard.org",\n  "company": {\n "name": "Romaguera-Crona",\n  "catchPhr
ase": "Multi-layered client-server neural-net",\n  "bs": "harness real-time
e-markets"\n }\n }

HTTPリクエストにパラメーターを渡す

URLを要求するだけでは不十分で、URLにパラメーターを渡す必要もあります。

パラメータは主にキー/値のペアとして渡されます、例えば-

 https://jsonplaceholder.typicode.com/users?id=9&username=Delphine

したがって、id = 9およびusername = Delphineとなります。 今、そのようなデータをリクエストのHttpモジュールに渡す方法を見ていきます。

import requests
payload = {'id': 9, 'username': 'Delphine'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users',
params = payload)
print(getdata.content)

詳細は、キーと値のペアのオブジェクトペイロードに保存され、get()メソッド内のparamsに渡されます。

出力

E:\prequests>python makeRequest.py
b'[\n {\n "id": 9,\n "name": "Glenna Reichert",\n "username": "Delphin
e",\n "email": "[email protected]",\n "address": {\n "street":
"Dayna Park",\n "suite": "Suite 449",\n "city": "Bartholomebury",\n
"zipcode": "76495-3109",\n "geo": {\n "lat": "24.6463",\n
"lng": "-168.8889"\n }\n },\n "phone": "(775)976-6794 x41206",\n "
website": "conrad.com",\n "company": {\n "name": "Yost and Sons",\n
"catchPhrase": "Switchable contextually-based project",\n "bs": "aggregate
real-time technologies"\n }\n }\n]'

応答でid = 9およびusername = Delphineの詳細を取得しています。

表示したい場合は、URLへの応答オブジェクトを使用して、パラメーターを渡した後のURLの外観。

import requests
payload = {'id': 9, 'username': 'Delphine'}
getdata = requests.get('https://jsonplaceholder.typicode.com/users',
params = payload)
print(getdata.url)

出力

E:\prequests>python makeRequest.py
https://jsonplaceholder.typicode.com/users?id=9&username=Delphine