PYTHON MEBY

PythonでHTTPリクエストを送信(requests, urllib.request)

この記事では、PythonでHTTPリクエストを送信する方法について説明します。requestsライブラリと組み込みのurllib.requestモジュールを使用した、GETリクエスト、POSTリクエスト、そしてエラーハンドリングの方法を学びます。

目次

requestsライブラリを使ったHTTPリクエスト

requestsライブラリは、HTTPリクエストを送信するためのシンプルで使いやすいライブラリです。pipでインストールできます。`pip install requests`

import requests

# GETリクエスト
response = requests.get('https://www.example.com')
print(response.status_code)
print(response.text)

# POSTリクエスト
data = {'key1': 'value1', 'key2': 'value2'}
response = requests.post('https://httpbin.org/post', data=data)
print(response.status_code)
print(response.json())

requests.get()メソッドはGETリクエストを送信し、requests.post()メソッドはPOSTリクエストを送信します。レスポンスのステータスコードと本文を確認できます。レスポンスのJSONデータを取得するには、response.json()を使用します。

urllib.requestモジュールを使ったHTTPリクエスト

Python標準ライブラリのurllib.requestモジュールでもHTTPリクエストを送信できます。requestsライブラリほど使いやすくありませんが、追加のライブラリをインストールする必要はありません。

import urllib.request
import urllib.parse

# GETリクエスト
url = 'https://www.example.com'
with urllib.request.urlopen(url) as response:
    html = response.read()
    print(response.status)
    print(html.decode('utf-8'))

# POSTリクエスト
url = 'https://httpbin.org/post'
data = urllib.parse.urlencode({'key1': 'value1', 'key2': 'value2'}).encode('utf-8')
req = urllib.request.Request(url, data=data, method='POST')
with urllib.request.urlopen(req) as response:
    response_body = response.read()
    print(response.getcode())
    print(response_body.decode('utf-8'))

urllib.request.urlopen()メソッドはGETリクエストを送信します。POSTリクエストを送信するには、urllib.request.Request()メソッドを使用し、method='POST'を指定します。レスポンスのエンコーディングに注意し、必要に応じてデコードしてください。

エラーハンドリング

HTTPリクエストは失敗する可能性があります。エラーを適切に処理するために、例外処理を使用します。

import requests

try:
    response = requests.get('https://www.example.com')
    response.raise_for_status() # ステータスコードが4xxまたは5xxの場合、例外を発生させる
    print(response.text)
except requests.exceptions.RequestException as e:
    print(f'HTTPリクエストエラー: {e}')

requests.exceptions.RequestExceptionは、requestsライブラリで発生する可能性のあるHTTPリクエスト関連の例外の基底クラスです。response.raise_for_status()メソッドは、ステータスコードが4xxまたは5xxの場合に例外を発生させます。

補足

requestsライブラリは、より多くの機能を提供し、使いやすいため、HTTPリクエストを送信する場合に推奨されます。urllib.requestモジュールは、標準ライブラリにあるため、追加のライブラリをインストールする必要がないという利点があります。

関連記事