◤Python無料教材配布◢ JobCodeメールマガジン実施中!

【Python】requestsとは?インストールから使い方まで徹底解説!

‎python-requests

Pythonで利用されるHTTPライブラリのrequestsに関する解説になります。

以下の内容をまとめています。

本記事のまとめ
  • requestsモジュールとは何か
  • requestsとSeleniumの違い
  • requestsのインストール
  • requestsの使い方
  • requests.get()の引数の使い方
  • responseオブジェクトの確認
筆者の経歴
  • SIer/Web系企業での実務経験があるフリーランスエンジニア
  • プログラミングスクールでの講師実績あり
  • HR領域によるエンジニア特化の採用代行を業務委託で兼務
【無料配布】Python基礎学習教材のプレゼント実施中!

本記事をお読み頂いているPython初学者向けに、メルマガ登録にてPython基礎学習教材の無料配布を実施しています。
以下に無料配布するPython資料をご紹介します。

無料配布するPython各資料
  • Python入門ガイド
  • Python基礎知識ガイド
  • tkinter基礎知識ガイド
  • 【tkinter製】デスクトップアプリフォルダ

Python学習に役立つ基礎知識ガイドを始め、アプリ開発時の基礎学習教材を用意しています。

各資料データに関しては不定期の更新になりますが、メルマガ登録者へ優先的にお知らせします。

記事ではお伝えできない内容を多分に含むため、メルマガ登録者限定にさせて頂きました。

ご興味がある人は以下からメルマガ登録を実施頂けますと幸いです。

\ メールアドレスのみで10秒登録! /

目次

requestsとは

Pythonのrequestsは、HTTP通信を利用したライブラリです。

HTTPは、クライアントとサーバーの間でデータをやりとりするためのプロトコル(規約)です。

また、HTTPは様々なメソッドを提供しており、以下の代表的なメソッドがあります。

メソッド名説明
requests.get()サーバーから情報を取得
requests.post()サーバーへ情報を送信
requests.put()サーバーの情報を更新
requests.delete()サーバーの情報を削除
requestsの代表的なメソッド

requestsは、特にWebスクレイピングに利用されたり、WebAPI連携によるデータ取得などに利用されます。

requestsとSeleniumの違い

requestsとSeleniumの違いは、ブラウザ操作・制御の有無になります。

requestsは、Seleniumと違ってブラウザ操作を実施しないため、URLをもとにサイト情報を取得します。

また、サイト情報をHTMLあるいはXMLなどのデータで取得するため、取得後はBeautifulSoupといった解析用ライブラリを利用する必要があります。

Seleniumにおける各メソッドの使い方を詳細に知りたい人は、「【業務自動化】Seleniumとは?インストールから使い方まで徹底解説!」を一読ください。

関連記事は、自動化やスクレイピングで利用されるseleniumの使い方を解説してます。
また、データ収集方法や待機処理などのコードも記載してます。

requestsのインストール

requestsはサードパーティライブラリであるため、別途インストールが必要になります。

.pyファイルにコードを記述する前にrequestsをインストールしておきましょう。

pip install requests

Macならターミナル、Windowsであればコマンドプロンプトで実施後、Successfullyが表示されたら完了です。

requestsのメソッドの使い方

改めて、代表的なrequestsのメソッドは以下の4つです。

メソッド名説明
requests.get()サーバーから情報を取得
requests.post()サーバーへ情報を送信
requests.put()サーバーの情報を更新
requests.delete()サーバーの情報を削除
requestsの代表的なメソッド

本記事では、Webスクレイピングを利用するため、.get()メソッドを重点的に解説します。

ログインが必要なケースで.session()メソッドを利用する場合があるため、ログイン処理を含めた解説は後述します。

requests.get()の引数の使い方

Webスクレイピングといったデータ収集などで頻繁に利用されるのがrequests.get()になります。

res = requests.get(URL, 任意の引数)

.get()メソッドを利用することで直感的に操作することができます。

また、以下が主な引数になります。

メソッド名必須/任意説明
URL必須対象URL
headers任意リクエスト時にヘッダーデータを辞書で指定
params任意リクエスト時にURLのクエリパラメータを辞書で指定
cookies任意リクエスト時にクッキーを辞書で指定
timeout任意リクエスト時のタイムアウトを指定
.get()メソッドの引数

スクレイピング業務では、引数にURLのみを利用することが多いです。

requests.get()によるresponseオブジェクトの確認

リクエスト後の戻り値(応答)として、responseオブジェクトが返ってきます。

以下がresponseオブジェクトの属性値になります。

属性説明
status_codeステータスコード
headersレスポンスヘッダーのデータ
contentレスポンスのバイナリデータ
textレスポンスのテキストデータ
encodingエンコーディング(変換方式:utf-8など)
cookiesクッキーデータ
responseオブジェクトの戻り値

ここでは、以下の条件でresponseオブジェクトがどのようなデータを返すか確認します。

引数データ
URLhttps://google.co.jp/
params{‘q’:’Python’}
responseオブジェクトの戻り値

上記の引数をrequests.get()メソッドに渡します。

import requests

url = 'https://google.co.jp'
params = {'q':'Python'}

response = requests.get(url, params=params)

responseオブジェクトの各属性を確認します。

レスポンスデータの解析を理解したい人は、「【チートシート】BeautifulSoup4とは?インストールから使い方まで徹底解説!」を一読ください。

関連記事は、beautifulsoup4に関するメソッドを中心に解説してます。
また、詳細な解析方法や使い方の具体的なコードも記載してます。

status_code(ステータスコード)

HTTPステータスコードは、サーバー側からのレスポンスの状況を確認するコードになります。

3桁が連なったコードであり、何番台かによって状況が異なります。

ステータスコードを理解することで、エラー処理などに役立ちます。

ステータスコード範囲説明
100~100~199Informational:リクエストは受信されて処理が継続する
200~200~299Success:リクエストが成功している
300~300~399Redirection :リダイレクトや遷移などリクエスト完了に追加処理が必要になる
400~400~499Client Error:クライアントからのリクエストに誤りがある
500~500~599Server Error :サーバ側でリクエスト処理に失敗する
ステータスコードの状況
print(response.status_code)
200

ここでは、ステータスコード200ということでリクエスト成功が表示されています。

headers(レスポンスヘッダー)

TTPレスポンスヘッダーは、サーバー側からのレスポンスのヘッダー部分になります。

#print(response.headers)
#分かりやすいように各要素のキー・値を表示します。
for key,value in response.headers.items():
    print(key,' || ',value)
Date  ||  Sun, 09 Jul 2023 09:38:27 GMT
Expires  ||  -1
Cache-Control  ||  private, max-age=0
Content-Type  ||  text/html; charset=Shift_JIS
Content-Security-Policy-Report-Only  ||  object-src 'none';base-uri 'self';script-src 'nonce-7SrrK0Im7SpdUnC2WbJcDg' 'strict-dynamic' 'report-sample' 'unsafe-eval' 'unsafe-inline' https: http:;report-uri https://csp.withgoogle.com/csp/gws/other-hp
P3P  ||  CP="This is not a P3P policy! See g.co/p3phelp for more info."
Content-Encoding  ||  gzip
Server  ||  gws
X-XSS-Protection  ||  0
X-Frame-Options  ||  SAMEORIGIN
Set-Cookie  ||  1P_JAR=2023-07-09-09; expires=Tue, 08-Aug-2023 09:38:27 GMT; path=/; domain=.google.co.jp; Secure, AEC=Ad49MVGlNWxOpzsuP1dxXBzyDc-XJ7sKN_seRn36DnWou5-eb3O9PzDS5A; expires=Fri, 05-Jan-2024 09:38:27 GMT; path=/; domain=.google.co.jp; Secure; HttpOnly; SameSite=lax, NID=511=FFsw48vTUH07Ww7lAC4LH0VtPBz6ooMAIdWdaikOyuzxHpfsfxc2HV-t9RU4mqfBLYVw8oQIPARM-UdR4ca88oETTZBxKdielU8UY2aMEWxnwC-A3StOG0zovHrIlpu0aMJ8ToLLX8EQtIxNd9BgKkCSDiyfikeWF6FNDOPpLKM; expires=Mon, 08-Jan-2024 09:38:27 GMT; path=/; domain=.google.co.jp; HttpOnly
Alt-Svc  ||  h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
Transfer-Encoding  ||  chunked

レスポンスヘッダーのデータは、取得するデータのオプションが記載されています。

content(レスポンスのバイナリデータ)

バイナリデータとは、PCが扱えるデータを指します。

そのため、人間では判断できないデータが含まれています。

print(response.content[:500])
b'<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="ja"><head><meta content="\x90\xa2\x8aE\x92\x86\x82\xcc\x82\xa0\x82\xe7\x82\xe4\x82\xe9\x8f\xee\x95\xf1\x82\xf0\x8c\x9f\x8d\xf5\x82\xb7\x82\xe9\x82\xbd\x82\xdf\x82\xcc\x83c\x81[\x83\x8b\x82\xf0\x92\xf1\x8b\x9f\x82\xb5\x82\xc4\x82\xa2\x82\xdc\x82\xb7\x81B\x82\xb3\x82\xdc\x82\xb4\x82\xdc\x82\xc8\x8c\x9f\x8d\xf5\x8b@\x94\\\x82\xf0\x8a\x88\x97p\x82\xb5\x82\xc4\x81A\x82\xa8\x92T\x82\xb5\x82\xcc\x8f\xee\x95\xf1\x82\xf0\x8c\xa9\x82\xc2\x82\xaf\x82\xc4\x82\xad\x82\xbe\x82\xb3\x82\xa2\x81B" name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="7SrrK0Im7SpdUnC2WbJcDg'

上記のコードは、レスポンスのバイナリデータから500文字までを表示しています。

text(レスポンスのテキストデータ)

responseオブジェクトに含まれるバイナリデータをヘッダーのエンコーディングでデコード(復元)することで、テキストデータに変換されます。

そのため、テキスト属性を利用して中身を確認します。

print(response.text[:500])
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="ja"><head><meta content="世界中のあらゆる情報を検索するためのツールを提供しています。さまざまな検索機能を活用して、お探しの情報を見つけてください。" name="description"><meta content="noodp" name="robots"><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="7SrrK0Im7SpdUnC2WbJcDg">(function(){var _g={kEI:'E4CqZNzaDuLF9APn2ruwBA',kEXPI:'0,1

バイナリデータと比較すると、日本語の文字列に変換されていることが分かります。

encoding(エンコーディング)

バイナリデータは、そのままで人間が扱えるデータになりません。

responseオブジェクトに含まれるバイナリデータをヘッダーのエンコーディングでデコード(復元)することで、テキストデータに変換します。

print(response.encoding)
Shift_JIS

表示結果から、’Shift_JIS’を利用していることが分かります。

cookies(レスポンスのクッキーデータ)

クッキーデータ(cookies)とは、対象URL(Webサイト)を保持するサーバー側から送信される情報で、端末(PC, スマホ)に保存されます(アクセス履歴)。

print(response.cookies)
<RequestsCookieJar[<Cookie 1P_JAR=2023-07-09-09 for .google.co.jp/>, <Cookie AEC=Ad49MVGlNWxOpzsuP1dxXBzyDc-XJ7sKN_seRn36DnWou5-eb3O9PzDS5A for .google.co.jp/>, <Cookie NID=511=FFsw48vTUH07Ww7lAC4LH0VtPBz6ooMAIdWdaikOyuzxHpfsfxc2HV-t9RU4mqfBLYVw8oQIPARM-UdR4ca88oETTZBxKdielU8UY2aMEWxnwC-A3StOG0zovHrIlpu0aMJ8ToLLX8EQtIxNd9BgKkCSDiyfikeWF6FNDOPpLKM for .google.co.jp/>]>

クッキーデータの中身は、アカウント情報・サイト訪問数や日時など様々な情報が記録されています。

requstsにおける.session()メソッドのログイン処理

ログインを必要とするWebサイトにてrequestsライブラリを利用する際に、都度GET/POSTのアクセス時にセッション切れで毎回ログイン処理を要求されるケースがあります。

セッション切れを回避するため、requestsライブラリは.session()メソッドが存在します。

import requests

username = "{ユーザーネーム}"
password = "{パスワード}"
login_url = "{対象サイトのログインページ}"

# セッションのインスタンス作成
session = requests.Session()
response = session.post(
    url=login_url,
    data={
        "username": username,
        "password": password,
    }
)

print(response.text)
# ログイン後に表示されるHTMLデータ取得

Sessionオブジェクトを使用すると、リクエスト間で特定のパラメータを永続化することでセッション切れを回避します。

ログイン処理ができない時の対処

対象サイトによっては、セッションなしのログイン処理によりセッション切れが発生するケースがあります。

理由は、対象サイト側でこちらが予期していないセキュリティ対策を講じている可能性があります。

考えられるセキュリティ対策の例
  • ユーザーエージェントの問題
  • ログイン画面の表示時点でCookie発行して整合性が取れない
  • トークン情報の付与が求められる

上記のようなケースでログイン処理が実行できない、あるいはセッション切れが発生する場合にセッションインスタンスを作成し、ログイン画面をGETしてCookieやトークン情報を得ておく必要があるでしょう。

requestsの主なメソッドと引数

requestsライブラリには多くのメソッドが存在します。

また、各メソッドに対して多くの引数があるため、改めて各メソッドと引数をまとめます。

スクロールできます
メソッド名主な引数説明
get()url, params, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, certHTTP GETリクエストを送信します
post()url, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, stream, verify, certHTTP POSTリクエストを送信します
put()url, data, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, certHTTP PUTリクエストを送信します
delete()url, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, certHTTP DELETEリクエストを送信します
head()url, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, certヘッダー情報のみを取得(本体なし)
options()url, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, cert対象リソースで使用可能なHTTPメソッドを取得します
patch()url, data, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, certHTTP PATCHリクエスト(部分更新)を送信します
request()method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, stream, verify, cert任意のHTTPメソッドでリクエストを送信します(上記各関数の汎用版)
requestsの主なメソッドと引数
スクロールできます
関数/オブジェクト説明
Session()複数のリクエストでクッキーやヘッダーなどを共有したいときに使うセッションオブジェクト
Request()リクエストの低レベルオブジェクト(主にSessionやPreparedRequestで使用)
PreparedRequest()RequestをHTTP送信可能な状態に準備したオブジェクト
Response()サーバーから返されたレスポンスオブジェクト(.status_codeや.textなどが使える)
exceptions例外モジュール.requests.exceptions.RequestExceptionなど多様な例外が定義されています
その他ユーティリティ関数/オブジェクト

requests.get()

requests.get()はHTTPのGETリクエストを送信する関数です。

URLに対してパラメータやヘッダーなどを付けてリクエストし、サーバーからのレスポンス(HTML,JSON,ファイルなど)を取得します。

スクロールできます
引数名説明
urlリクエストを送信する対象のURL(必須)
paramsクエリパラメータ(辞書やタプル形式で渡す)
headersHTTPヘッダー情報(辞書)
cookiesクッキー情報(辞書)
auth認証情報(例:(ユーザー名, パスワード))
timeoutタイムアウト時間(秒単位)
allow_redirectsリダイレクトの許可(デフォルトはTrue)
proxiesプロキシ設定(辞書形式)
streamレスポンスをストリーミングで受け取る(大きなファイルなど)
verifySSL証明書の検証(True/Falseやパス指定)
certクライアント証明書ファイルのパスまたは (cert, key) タプル
利用可能な引数一覧
url(必須)
import requests

response = requests.get('https://example.com')
print(response.status_code)
params
params = {'q': 'python', 'page': 2}
response = requests.get('https://example.com/search', params=params)
print(response.url)  # クエリ付きURLが表示される
headers
headers = {'User-Agent': 'my-app/1.0'}
response = requests.get('https://example.com', headers=headers)
cookies
cookies = {'session_id': 'abc123'}
response = requests.get('https://example.com/dashboard', cookies=cookies)
auth
from requests.auth import HTTPBasicAuth

response = requests.get('https://example.com/secure', auth=HTTPBasicAuth('user', 'pass'))
timeout
response = requests.get('https://example.com', timeout=3)
allow_redirects
response = requests.get('https://example.com/redirect', allow_redirects=False)
proxies
proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'https://10.10.1.10:1080'
}
response = requests.get('https://example.com', proxies=proxies)
stream
response = requests.get('https://example.com/largefile', stream=True)
for chunk in response.iter_content(chunk_size=1024):
    print(chunk)
verify
# 証明書を検証しない(自己署名証明書など)
response = requests.get('https://example.com', verify=False)
cert
response = requests.get('https://example.com', cert=('/path/client.crt', '/path/client.key'))

requests.post()

requests.post()はHTTPのPOSTリクエストを送信する関数です。

主にサーバーにフォームデータやJSONデータを送信するときに使用されます。

サーバー側でデータの追加・更新処理が行われることが一般的です。

スクロールできます
引数名説明
urlリクエストを送信する対象のURL(必須)
dataフォームデータやバイナリデータなど(辞書・タプル・文字列・ファイルなど)
jsonJSON形式のデータ(Pythonの辞書で渡すと自動的にJSONに変換される)
headersHTTPヘッダー情報(例: Content-Type, Authorization など)
cookiesクッキー情報(辞書)
filesファイル送信に使うデータ(辞書形式でファイルオブジェクトを渡す)
auth認証情報(例: (ユーザー名, パスワード))
timeoutタイムアウト時間(秒数)
allow_redirectsリダイレクトの許可(デフォルトはTrue)
proxiesプロキシ設定(例: {‘http’: ‘http://proxy.example.com:8080’})
streamレスポンスをストリーミングで受信する(True/False)
verifySSL証明書の検証(True/Falseまたは証明書パス)
certクライアント証明書のパスまたは (cert, key) タプル
利用可能な引数一覧
url(必須)
import requests

response = requests.post('https://httpbin.org/post')
print(response.status_code)
data(フォームデータ送信)
payload = {'username': 'test', 'password': 'secret'}
response = requests.post('https://httpbin.org/post', data=payload)
print(response.text)
json(JSON形式で送信)
json_data = {'title': 'AI', 'category': 'Technology'}
response = requests.post('https://httpbin.org/post', json=json_data)
print(response.json())
headers(ヘッダーの追加)
headers = {'Authorization': 'Bearer xxxxx'}
response = requests.post('https://httpbin.org/post', headers=headers)
cookies
cookies = {'session_id': 'abc123'}
response = requests.post('https://httpbin.org/post', cookies=cookies)
files(ファイルアップロード)
files = {'file': open('example.txt', 'rb')}
response = requests.post('https://httpbin.org/post', files=files)
print(response.text)
auth(基本認証)
from requests.auth import HTTPBasicAuth

response = requests.post('https://httpbin.org/basic-auth/user/pass', auth=HTTPBasicAuth('user', 'pass'))
timeout
response = requests.post('https://httpbin.org/post', timeout=5)
allow_redirects
response = requests.post('https://httpbin.org/redirect-to?url=/get', allow_redirects=False)
proxies
proxies = {'http': 'http://10.10.1.10:3128'}
response = requests.post('https://httpbin.org/post', proxies=proxies)
stream
response = requests.post('https://httpbin.org/post', stream=True)
for line in response.iter_lines():
    print(line)
verify(SSL検証無効化)
response = requests.post('https://example.com', verify=False)
cert(クライアント証明書)
response = requests.post('https://example.com', cert=('/path/client.crt', '/path/client.key'))

requests.put()

requests.put()はHTTPのPUTリクエストを送信する関数です。

指定したリソースの完全な置き換え(更新)を行う際に使います。

例えば、特定IDのユーザー情報を全て新しい情報に置き換える場合などに使用します。

一般にPOSTは「新規作成」、PUTは「完全更新」に使います。

スクロールできます
引数名説明
urlリクエストを送信する対象のURL(必須)
data更新するデータ(辞書・タプル・文字列・ファイルなど)
jsonJSON形式のデータ(Pythonの辞書など)
headersHTTPヘッダー情報(例: Content-Type, Authorization など)
cookiesクッキー情報(辞書)
filesファイル送信に使うデータ(辞書形式でファイルオブジェクトを渡す)
auth認証情報(例: (ユーザー名, パスワード))
timeoutタイムアウト時間(秒数)
allow_redirectsリダイレクトの許可(デフォルトはTrue)
proxiesプロキシ設定(辞書形式)
streamレスポンスをストリーミングで受信する(True/False)
verifySSL証明書の検証(True/Falseまたは証明書パス)
certクライアント証明書のパスまたは (cert, key) タプル
利用可能な引数一覧
url(必須)
import requests

response = requests.put('https://httpbin.org/put')
print(response.status_code)
data(フォームデータなどを更新)
payload = {'name': 'Taro', 'email': 'taro@example.com'}
response = requests.put('https://httpbin.org/put', data=payload)
print(response.text)
json(JSONデータとして送信)
json_data = {'id': 101, 'status': 'active'}
response = requests.put('https://httpbin.org/put', json=json_data)
print(response.json())
headers(ヘッダーを指定)
headers = {'Authorization': 'Bearer mytoken'}
response = requests.put('https://httpbin.org/put', headers=headers)
cookies
cookies = {'user_token': 'abc123'}
response = requests.put('https://httpbin.org/put', cookies=cookies)
files(ファイル送信)
files = {'upload': open('document.pdf', 'rb')}
response = requests.put('https://httpbin.org/put', files=files)
auth(基本認証)
from requests.auth import HTTPBasicAuth

response = requests.put('https://httpbin.org/put', auth=HTTPBasicAuth('user', 'pass'))
timeout
response = requests.put('https://httpbin.org/put', timeout=5)
allow_redirects
response = requests.put('https://httpbin.org/redirect-to?url=/get', allow_redirects=False)
proxies
proxies = {'http': 'http://10.10.1.10:3128'}
response = requests.put('https://httpbin.org/put', proxies=proxies)
stream
response = requests.put('https://httpbin.org/put', stream=True)
for line in response.iter_lines():
    print(line)
verify(SSL検証をスキップ)
response = requests.put('https://example.com', verify=False)
cert(クライアント証明書を使う)
response = requests.put('https://example.com', cert=('/path/client.crt', '/path/client.key'))

requests.delete()

requests.delete()はHTTPのDELETEリクエストを送信する関数です。

主に、指定したリソースを削除するために使用します。

RESTful APIでは、エンドポイントに対してリソースを削除する際に使います。

スクロールできます
引数名説明
urlリクエスト先のURL(必須)
paramsURLクエリパラメータ(辞書やタプル)
headersHTTPヘッダー情報
cookiesクッキー情報(辞書)
auth認証情報(例: (ユーザー名, パスワード))
timeoutタイムアウト時間(秒)
allow_redirectsリダイレクトを許可するか(デフォルトは True)
proxiesプロキシ設定(辞書形式)
streamレスポンスをストリーミングで受け取る(True/False)
verifySSL証明書を検証するか
certクライアント証明書のパスまたは (cert, key) のタプル
利用可能な引数一覧
url(必須)
import requests

response = requests.delete('https://httpbin.org/delete')
print(response.status_code)
params(クエリパラメータ)
params = {'id': 123}
response = requests.delete('https://httpbin.org/delete', params=params)
print(response.url)  # => https://httpbin.org/delete?id=123
headers(カスタムヘッダー)
headers = {'Authorization': 'Bearer mytoken'}
response = requests.delete('https://httpbin.org/delete', headers=headers)
cookies(クッキーを送信)
cookies = {'session_id': 'abc123'}
response = requests.delete('https://httpbin.org/delete', cookies=cookies)
auth(基本認証)
from requests.auth import HTTPBasicAuth

response = requests.delete('https://httpbin.org/delete', auth=HTTPBasicAuth('user', 'pass'))
timeout(タイムアウト設定)
response = requests.delete('https://httpbin.org/delete', timeout=5)
allow_redirects(リダイレクトの可否)
response = requests.delete('https://httpbin.org/redirect-to?url=/get', allow_redirects=False)
print(response.status_code)
proxies(プロキシ設定)
proxies = {'http': 'http://10.10.1.10:3128'}
response = requests.delete('https://httpbin.org/delete', proxies=proxies)
stream(レスポンスをストリームとして受信)
response = requests.delete('https://httpbin.org/delete', stream=True)
for chunk in response.iter_content(chunk_size=128):
    print(chunk)
verify(SSL証明書の検証を無効化)
response = requests.delete('https://example.com', verify=False)
cert(クライアント証明書の利用)
response = requests.delete('https://example.com', cert=('/path/client.crt', '/path/client.key'))

requests.head()

requests.head()はHTTPのHEADリクエストを送信する関数です。

このリクエストは、レスポンスボディなしでヘッダーだけ取得するために使います。

リソースの存在確認/更新日時取得/Content-Type/Lengthなどの情報を調べる用途に便利です。

GETリクエストと似ていますが、レスポンスの本文が返ってこないのが特徴です。

スクロールできます
引数名説明
urlリクエストを送るURL(必須)
paramsクエリパラメータ(辞書やタプル)
headersリクエストヘッダー(例: User-Agent, Authorization)
cookiesクッキー情報(辞書)
auth認証情報(例: (ユーザー名, パスワード))
timeoutタイムアウト時間(秒)
allow_redirectsリダイレクトの可否(デフォルトは False)
proxiesプロキシ設定(辞書形式)
streamレスポンスをストリーミングで受け取る(True/False)
verifySSL証明書を検証するか
certクライアント証明書を指定
利用可能な引数一覧
url(必須)
import requests

response = requests.head('https://httpbin.org/get')
print(response.status_code)
print(response.headers)
params(クエリパラメータ)
params = {'id': 456}
response = requests.head('https://httpbin.org/get', params=params)
print(response.url)  # => https://httpbin.org/get?id=456
headers(リクエストヘッダー)
headers = {'User-Agent': 'MyApp'}
response = requests.head('https://httpbin.org/get', headers=headers)
cookies(クッキーの送信)
cookies = {'session': 'xyz789'}
response = requests.head('https://httpbin.org/get', cookies=cookies)
auth(ベーシック認証)
from requests.auth import HTTPBasicAuth

response = requests.head('https://httpbin.org/basic-auth/user/pass', auth=HTTPBasicAuth('user', 'pass'))
timeout(タイムアウト指定)
response = requests.head('https://httpbin.org/get', timeout=3)
allow_redirects(リダイレクトを許可するか)
response = requests.head('https://httpbin.org/redirect-to?url=/get', allow_redirects=False)
print(response.status_code)
proxies(プロキシ設定)
proxies = {'https': 'http://10.10.1.10:1080'}
response = requests.head('https://httpbin.org/get', proxies=proxies)
stream(ストリーミング有効化)
response = requests.head('https://httpbin.org/get', stream=True)
print(response.headers.get('Content-Length'))
verify(SSL証明書の検証を無効化)
response = requests.head('https://example.com', verify=False)
cert(クライアント証明書を利用)
response = requests.head('https://example.com', cert=('/path/to/client.crt', '/path/to/client.key'))

requests.options()

requests.options()はHTTPのOPTIONSリクエストを送信する関数です。

指定されたURLでサポートされているHTTPメソッドや通信オプションを問い合わせる際に使用します。

主な用途
  • CORS(クロスオリジン)通信のプリフライトリクエスト
  • APIエンドポイントが対応してるメソッド(GET,POSTなど)の確認
  • サーバーのオプション確認
スクロールできます
引数名説明
urlリクエスト対象のURL(必須)
paramsクエリパラメータ(辞書やタプル)
headersHTTPリクエストヘッダー
cookiesクッキー情報(辞書)
auth認証情報(例: (ユーザー名, パスワード))
timeoutタイムアウト時間(秒)
allow_redirectsリダイレクトの許可(デフォルトは True)
proxiesプロキシ設定(辞書形式)
streamレスポンスをストリーミングで受け取る(True/False)
verifySSL証明書を検証するか
certクライアント証明書を指定
利用可能な引数一覧
url(必須)
import requests

response = requests.options('https://httpbin.org/get')
print(response.status_code)
print(response.headers['Allow'])  # サポートされているメソッド
params(クエリパラメータ)
params = {'check': 'true'}
response = requests.options('https://httpbin.org/get', params=params)
print(response.url)
headers(カスタムヘッダー)
headers = {'Access-Control-Request-Method': 'POST'}
response = requests.options('https://httpbin.org/post', headers=headers)
print(response.headers.get('Allow'))
cookies(クッキーを送信)
cookies = {'session_id': 'abc123'}
response = requests.options('https://httpbin.org/get', cookies=cookies)
auth(ベーシック認証)
from requests.auth import HTTPBasicAuth

response = requests.options('https://httpbin.org/basic-auth/user/pass', auth=HTTPBasicAuth('user', 'pass'))
timeout(タイムアウト秒数)
response = requests.options('https://httpbin.org/get', timeout=5)
allow_redirects(リダイレクト可否)
response = requests.options('https://httpbin.org/redirect-to?url=/get', allow_redirects=False)
print(response.status_code)
proxies(プロキシ経由)
proxies = {'http': 'http://10.10.1.10:3128'}
response = requests.options('https://httpbin.org/get', proxies=proxies)
stream(ストリーミング有効)
response = requests.options('https://httpbin.org/get', stream=True)
print(response.headers.get('Allow'))
verify(SSL証明書の検証無効化)
response = requests.options('https://example.com', verify=False)
cert(クライアント証明書の利用)
response = requests.options('https://example.com', cert=('/path/client.crt', '/path/client.key'))

requests.patch()

requests.patch()はHTTPのPATCHリクエストを送信する関数です。

既存リソースの一部だけを更新したいときに使います。(PUTは全体更新に対し、PATCHは部分更新)

REST APIでのレコードの一部修正(例:ユーザーの名前だけ変更)などに利用します。

スクロールできます
引数名説明
urlリクエスト送信先のURL(必須)
dataフォームデータや辞書(application/x-www-form-urlencoded)
jsonJSONデータ(Pythonの辞書を自動的にJSONに変換)
headersリクエストヘッダー
cookiesクッキー情報(辞書)
authベーシック認証 (ユーザー名, パスワード)
paramsクエリパラメータ
timeoutタイムアウト秒数
allow_redirectsリダイレクトの許可(デフォルトは True)
proxiesプロキシサーバの設定
streamレスポンスをストリーミングで取得
verifySSL証明書の検証
certクライアント証明書の指定
利用可能な引数一覧
url(必須)
import requests

response = requests.patch('https://httpbin.org/patch')
print(response.status_code)
print(response.json())
data(部分更新データ:フォーム形式)
data = {'email': 'new@example.com'}
response = requests.patch('https://httpbin.org/patch', data=data)
print(response.json())
json(部分更新データ:JSON形式)
json_data = {'email': 'new@example.com'}
response = requests.patch('https://httpbin.org/patch', json=json_data)
print(response.json())
headers(カスタムヘッダー)
headers = {'Authorization': 'Bearer your_token'}
response = requests.patch('https://httpbin.org/patch', json={'name': 'John'}, headers=headers)
cookies(クッキーの送信)
cookies = {'session_id': 'abc123'}
response = requests.patch('https://httpbin.org/patch', json={'role': 'admin'}, cookies=cookies)
auth(ベーシック認証)
from requests.auth import HTTPBasicAuth

response = requests.patch('https://httpbin.org/patch', auth=HTTPBasicAuth('user', 'pass'), json={'status': 'active'})
params(URLクエリパラメータ)
params = {'debug': 'true'}
response = requests.patch('https://httpbin.org/patch', json={'level': 'moderator'}, params=params)
timeout(タイムアウト指定)
response = requests.patch('https://httpbin.org/patch', json={'key': 'value'}, timeout=5)
allow_redirects(リダイレクト制御)
response = requests.patch('https://httpbin.org/redirect-to?url=/patch', allow_redirects=False)
print(response.status_code)
proxies(プロキシ使用)
proxies = {'http': 'http://10.10.1.10:3128'}
response = requests.patch('https://httpbin.org/patch', json={'name': 'proxy-test'}, proxies=proxies)
stream(ストリーミング応答)
response = requests.patch('https://httpbin.org/patch', json={'stream': True}, stream=True)
print(response.raw)
verify(SSL証明書検証を無効)
response = requests.patch('https://example.com/api', verify=False)
cert(クライアント証明書の指定)
response = requests.patch('https://example.com/api', cert=('/path/client.crt', '/path/client.key'))

requests.request()

requests.request()は、requestsライブラリの最も汎用的な低レベルメソッドで、GET/POST/PUTDELETEなどあらゆるHTTPメソッドを文字列で指定して送信できます。

通常はrequests.get()やrequests.post()などの専用関数を使えば十分ですが、メソッド名を動的に扱いたい場合やカスタム処理をしたい場合に便利です。

スクロールできます
引数名説明
method使用するHTTPメソッド名(文字列:例 ‘GET’, ‘POST’、必須
urlリクエストの送信先URL(必須)
paramsクエリパラメータ(?key=value のような形式)
dataフォームデータなど(application/x-www-form-urlencoded)
jsonJSON形式で送信するデータ(辞書を指定)
headersHTTPヘッダー(辞書形式)
cookiesクッキーの送信(辞書形式)
filesファイルのアップロード用データ(例:{‘file’: open(‘file.txt’, ‘rb’)})
authベーシック認証((ユーザー名, パスワード))
timeoutタイムアウト秒数
allow_redirectsリダイレクトを許可するか(デフォルト:True)
proxiesプロキシの指定
streamストリーミングで受信するか
verifySSL証明書の検証
certクライアント証明書の指定
利用可能な引数一覧
基本的なGETリクエスト
import requests

response = requests.request(method='GET', url='https://httpbin.org/get')
print(response.json())
POSTリクエスト + JSONデータ送信
response = requests.request(
    method='POST',
    url='https://httpbin.org/post',
    json={'name': 'ChatGPT', 'type': 'AI'}
)
print(response.json())
data(フォーム形式の送信)
response = requests.request(
    method='POST',
    url='https://httpbin.org/post',
    data={'username': 'admin', 'password': '1234'}
)
params(クエリパラメータ付き)
response = requests.request(
    method='GET',
    url='https://httpbin.org/get',
    params={'q': 'python', 'page': 2}
)
print(response.url)
headers(カスタムヘッダー)
response = requests.request(
    method='GET',
    url='https://httpbin.org/headers',
    headers={'User-Agent': 'my-custom-agent'}
)
cookies(クッキー送信)
response = requests.request(
    method='GET',
    url='https://httpbin.org/cookies',
    cookies={'session': 'abc123'}
)
files(ファイルアップロード)
with open('example.txt', 'rb') as f:
    response = requests.request(
        method='POST',
        url='https://httpbin.org/post',
        files={'file': f}
    )
auth(ベーシック認証)
from requests.auth import HTTPBasicAuth

response = requests.request(
    method='GET',
    url='https://httpbin.org/basic-auth/user/pass',
    auth=HTTPBasicAuth('user', 'pass')
)
timeout(タイムアウト指定)
response = requests.request(
    method='GET',
    url='https://httpbin.org/delay/3',
    timeout=5
)
allow_redirects(リダイレクト禁止)
response = requests.request(
    method='GET',
    url='https://httpbin.org/redirect/1',
    allow_redirects=False
)
print(response.status_code)
proxies(プロキシ設定)
proxies = {'http': 'http://10.10.1.10:3128'}
response = requests.request(
    method='GET',
    url='https://httpbin.org/get',
    proxies=proxies
)
verify(SSL証明書の検証を無効に)
response = requests.request(
    method='GET',
    url='https://self-signed.badssl.com/',
    verify=False
)
cert(クライアント証明書の指定)
response = requests.request(
    method='GET',
    url='https://example.com/secure-api',
    cert=('/path/client.crt', '/path/client.key')
)

requests.Session()

requests.Session()は、HTTPリクエストにおいて接続の再利用/共通設定の保持を可能にする「セッションオブジェクト」を生成します。

主な用途
  • Cookieの自動保持
  • ヘッダーや認証情報の使い回し
  • 複数リクエスト間での接続再利用による高速化
スクロールできます
属性・メソッド名説明
Session.headers各リクエストで共通使用するHTTPヘッダー(辞書)
Session.auth共通のベーシック認証情報を設定
Session.cookiesCookieの自動管理・手動設定
Session.params共通クエリパラメータを設定
Session.proxiesプロキシの設定
Session.verifySSL検証を一括で設定
Session.certクライアント証明書の設定
Session.get()など各HTTPメソッド(GET, POSTなど)をセッション経由で実行
Session.request()任意メソッドをセッション経由で実行
Session.close()セッションの明示的な終了(推奨)
主な属性・設定メソッド一覧
基本的な使い方(セッションを作成して使う)
import requests

session = requests.Session()

# 共通のヘッダーを設定
session.headers.update({'User-Agent': 'my-app/1.0'})

# GETリクエスト
response = session.get('https://httpbin.org/get')
print(response.json())

# セッションを明示的に閉じる
session.close()
Cookieの自動保持
session = requests.Session()

# Cookieをセット
session.get('https://httpbin.org/cookies/set?name=value')

# 自動でCookieを送信してくれる
response = session.get('https://httpbin.org/cookies')
print(response.json())
共通ヘッダーの設定
session = requests.Session()
session.headers.update({'Authorization': 'Bearer YOUR_TOKEN'})

response = session.get('https://httpbin.org/headers')
print(response.json())
認証の使い回し
from requests.auth import HTTPBasicAuth

session = requests.Session()
session.auth = HTTPBasicAuth('user', 'pass')

response = session.get('https://httpbin.org/basic-auth/user/pass')
print(response.status_code)  # 200 if success
クエリパラメータの共通化
session = requests.Session()
session.params = {'lang': 'ja'}

response = session.get('https://httpbin.org/get')
print(response.url)  # https://httpbin.org/get?lang=ja
複数回のPOSTに同じ設定で対応
session = requests.Session()
session.headers.update({'Content-Type': 'application/json'})

data = {'key': 'value'}
response1 = session.post('https://httpbin.org/post', json=data)
response2 = session.post('https://httpbin.org/post', json=data)
セッションの明示的な終了
session = requests.Session()
try:
    response = session.get('https://httpbin.org/get')
finally:
    session.close()

with文を使うと、自動でセッションを閉じることも可能です

with requests.Session() as session:
    session.headers.update({'User-Agent': 'my-app'})
    response = session.get('https://httpbin.org/get')
    print(response.status_code)
スクロールできます
利用目的Session()の利点
複数のAPIアクセスヘッダーや認証、Cookieを毎回設定しなくて良い
高速化コネクションプールを再利用(TCPの再確立を省略)
セキュアな設定共通化verify, cert, proxies などを一括管理できる
Session()のまとめ

requests.Request()

requests.Request()は、リクエスト内容を手動で構成する低レベルAPIです。

このオブジェクトは.prepare()を使ってPreparedRequestに変換し、Session.send()に渡すことでHTTPリクエストを送信します。

通常のrequests.get()やrequests.post()ではなく、リクエスト内容を柔軟にカスタマイズしたい場合に使用します。

import requests

req = requests.Request(
    method='GET',
    url='https://httpbin.org/get',
    params={'q': 'chatgpt'}
)

prepared = req.prepare()

with requests.Session() as session:
    response = session.send(prepared)
    print(response.status_code)
スクロールできます
引数名説明
methodHTTPメソッド(’GET’, ‘POST’, など)※必須
urlリクエストURL(必須)
headersリクエストヘッダー(辞書形式)
filesアップロードファイル({‘file’: file_obj})
dataフォームデータやペイロード(application/x-www-form-urlencoded)
jsonJSON形式データ(辞書形式)
paramsクエリパラメータ(URL末尾の ?key=value)
auth認証情報(例:(‘user’, ‘pass’))
cookiesクッキー情報(辞書形式)
hooksレスポンスフック
headersHTTPヘッダーの指定
主な属性・設定メソッド一覧
method, url, params(クエリパラメータ)
import requests

req = requests.Request(
    method='GET',
    url='https://httpbin.org/get',
    params={'search': 'python'}
)
prepared = req.prepare()

with requests.Session() as s:
    res = s.send(prepared)
    print(res.json())
data, headers(フォームデータ送信)
req = requests.Request(
    method='POST',
    url='https://httpbin.org/post',
    data={'username': 'admin'},
    headers={'Content-Type': 'application/x-www-form-urlencoded'}
)
prepared = req.prepare()

with requests.Session() as s:
    res = s.send(prepared)
    print(res.json())
json(JSONデータ送信)
req = requests.Request(
    method='POST',
    url='https://httpbin.org/post',
    json={'key': 'value'}
)
prepared = req.prepare()

with requests.Session() as s:
    res = s.send(prepared)
    print(res.json())
auth(ベーシック認証)
req = requests.Request(
    method='GET',
    url='https://httpbin.org/basic-auth/user/pass',
    auth=('user', 'pass')
)
prepared = req.prepare()

with requests.Session() as s:
    res = s.send(prepared)
    print(res.status_code)  # 200 if success
cookies
req = requests.Request(
    method='GET',
    url='https://httpbin.org/cookies',
    cookies={'sessionid': 'abc123'}
)
prepared = req.prepare()

with requests.Session() as s:
    res = s.send(prepared)
    print(res.json())
hooks(レスポンスフック)
def response_hook(response, *args, **kwargs):
    print("フック実行:", response.status_code)

req = requests.Request(
    method='GET',
    url='https://httpbin.org/get',
    hooks={'response': response_hook}
)
prepared = req.prepare()

with requests.Session() as s:
    res = s.send(prepared)
スクロールできます
活用シーン利点
複数のリクエストを事前に組み立てたいリクエスト構築と送信の分離ができる
テスト時にカスタムリクエストを再送したいリクエストの再利用が容易
特定条件でのみヘッダーやデータを切り替えたい柔軟に組み立て可能
活用シーンのまとめ

requests.PreparedRequest()

requests.PreparedRequestは、送信可能なリクエストを完全に構成したオブジェクトです。

requests.Request(…).prepare()によって作成され、Session.send()で送信します。

主な用途
  • 低レベルでリクエストを手動で構築・調整したいとき
  • 再送信やログ出力のために完全なリクエスト情報を確認・保持したいとき
スクロールできます
属性名説明
methodHTTPメソッド(’GET’、’POST’ など)
url最終的に構築されたURL(クエリ含む)
headers実際に送信されるヘッダー(辞書)
bodyリクエストボディ(エンコード済み)
cookiesCookieヘッダーに含まれる情報
prepare_method()HTTPメソッドを準備する(通常は内部使用)
prepare_url(url, params)URLとクエリを組み合わせる(内部使用)
prepare_headers(headers)ヘッダーを構築(内部使用)
prepare_body()ボディデータを準備(内部使用)
主な属性一覧
生成方法(基本構文)
from requests import Request, Session

req = Request(
    method='POST',
    url='https://httpbin.org/post',
    data={'key': 'value'}
)

prepared = req.prepare()

with Session() as session:
    response = session.send(prepared)
URLとクエリ文字列の確認
from requests import Request

req = Request(
    method='GET',
    url='https://httpbin.org/get',
    params={'lang': 'ja'}
)
prepared = req.prepare()

print(prepared.url)  # → https://httpbin.org/get?lang=ja
実際に送信されるヘッダーを確認
print(prepared.headers)
ボディの中身(formやJSON)
print(prepared.body)  # application/x-www-form-urlencoded なら b'key=value'
PreparedRequestをセッションで送信
from requests import Session

with Session() as session:
    response = session.send(prepared)
    print(response.status_code)
全体の例:PreparedRequestの構成と送信
import requests

# Step 1: Requestオブジェクトを作成
req = requests.Request(
    method='POST',
    url='https://httpbin.org/post',
    headers={'User-Agent': 'my-app'},
    data={'username': 'admin'}
)

# Step 2: PreparedRequestに変換
prepared = req.prepare()

# Step 3: セッションで送信
with requests.Session() as session:
    response = session.send(prepared)
    print("Status:", response.status_code)
    print("Sent Headers:", prepared.headers)
    print("Sent Body:", prepared.body)
スクロールできます
利用シーンメリット
高度なリクエスト制御リクエスト前にすべての値を確認・編集できる
テスト・ログ出力実際に送られる内容を可視化できる
条件に応じて動的リクエスト構築.prepare()を使って柔軟な対応が可能
利用シーンとメリット
注意点
  • PreparedRequestは直接作成できない
  • requests.Request(…).prepare()を通して生成
  • 一度生成されたPreparedRequestは不変(immutable)

requests.Response()

requests.Response()は、HTTPリクエストの応答(レスポンス)を表すオブジェクトです。

requests.get()やrequests.post()などの戻り値として返されます。

レスポンスの内容(本文・ステータス・ヘッダーなど)を取得・解析するために使用します。

スクロールできます
属性/メソッド名説明
.status_codeHTTPステータスコード(例:200, 404)
.textデコード済みのレスポンス本文(文字列)
.content生のバイナリレスポンス本文(bytes)
.json()JSONレスポンスを辞書として取得(dict)
.headersレスポンスヘッダー(辞書形式)
.cookiesサーバーから送られたクッキー(RequestsCookieJar)
.url実際にアクセスしたURL
.okステータスが200〜399なら True
.reasonステータスメッセージ(例:’OK’, ‘Not Found’)
.elapsedリクエストからレスポンスまでの時間(datetime.timedelta)
.raise_for_status()エラー(4xx/5xx)時に HTTPError を発生させる
.encodingテキストのデコードに使われたエンコーディング
.is_redirectリダイレクトかどうか(True/False)
.historyリダイレクト履歴(リスト)
主な属性・メソッド一覧
import requests

response = requests.get('https://httpbin.org/get')

print(response.status_code)      # 200
print(response.text)             # レスポンス本文(文字列)
print(response.json())           # JSONを辞書に変換
print(response.headers['Content-Type'])  # レスポンスヘッダー
.status_code
print(response.status_code)  # 例: 200, 404
.text(HTMLやJSONを文字列として取得)
print(response.text)  # HTMLやJSONが文字列で返る
.content(画像などバイナリデータ)
with open('image.png', 'wb') as f:
    f.write(response.content)
.json()(JSONを辞書にパース)
data = response.json()
print(data['url'])  # https://httpbin.org/get
.headers(レスポンスヘッダー)
print(response.headers['Content-Type'])  # 例: application/json
.cookies
print(response.cookies.get_dict())  # {'sessionid': 'abc123'}
.raise_for_status()(エラーハンドリング)
try:
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("エラー発生:", e)
.elapsed(応答時間)
print(response.elapsed.total_seconds())  # 例: 0.124
.is_redirectと.history
if response.is_redirect:
    print("リダイレクトされました")

print(response.history)  # 過去のレスポンスのリスト
実用例まとめ
import requests

response = requests.get('https://httpbin.org/json')

if response.ok:
    print("ステータスOK:", response.status_code)
    data = response.json()
    print("スライドタイトル:", data['slideshow']['title'])
else:
    print("エラー:", response.status_code)

requests.exceptions

requests.exceptionsは、HTTP通信に関連する例外(エラー)を管理するモジュールです。

requestsライブラリの使用中に発生しうる全てのエラーは、ここに含まれる例外クラスのいずれかになります。

スクロールできます
例外クラス名説明
RequestExceptionすべての例外の基底クラス(親クラス)
HTTPErrorHTTPエラー(ステータスコードが 4xx, 5xx のとき)
ConnectionErrorネットワーク接続エラー(DNS失敗、接続タイムアウトなど)
Timeoutタイムアウト(接続や応答に時間がかかりすぎた場合)
ConnectTimeout接続タイムアウト(接続確立時に発生)
ReadTimeoutサーバーからの応答待ちでタイムアウト
TooManyRedirectsリダイレクトが多すぎるとき
URLRequiredURLが不正または指定されていないとき
MissingSchemaURLスキーマ(http://など)が不足している
InvalidSchemaサポートされていないURLスキーマ
InvalidURL無効なURL形式
ChunkedEncodingErrorチャンク転送エンコーディングのエラー
ContentDecodingError応答のデコード中に発生したエラー
StreamConsumedErrorストリームがすでに読み込まれていて再使用できない
RetryError再試行処理に失敗したとき(urllib3の内部で発生)
UnrewindableBodyErrorボディを巻き戻せずに再送信できないとき
主な例外クラス一覧
HTTPError
import requests

try:
    response = requests.get("https://httpbin.org/status/404")
    response.raise_for_status()
except requests.exceptions.HTTPError as e:
    print("HTTPエラー発生:", e)
ConnectionError
try:
    requests.get("https://nonexistent.example.com")
except requests.exceptions.ConnectionError as e:
    print("接続エラー:", e)
Timeout, ConnectTimeout, ReadTimeout
try:
    requests.get("https://httpbin.org/delay/10", timeout=2)
except requests.exceptions.Timeout as e:
    print("タイムアウト:", e)
TooManyRedirects
try:
    requests.get("https://httpbin.org/redirect/20")
except requests.exceptions.TooManyRedirects as e:
    print("リダイレクトが多すぎます:", e)
MissingSchema, InvalidSchema, InvalidURL
try:
    requests.get("example.com")  # スキーマ不足
except requests.exceptions.MissingSchema as e:
    print("スキーマが不足しています:", e)

try:
    requests.get("ftp://example.com")  # 不正なスキーマ
except requests.exceptions.InvalidSchema as e:
    print("サポートされていないスキーマ:", e)
ChunkedEncodingError, ContentDecodingError

これらは主にサーバー側の応答がおかしいときに発生するため擬似的なテスト環境が必要ですが、使用時にはtry-exceptでまとめて処理します。

例外を一括でハンドリング(推奨方法)
try:
    response = requests.get("https://httpbin.org/get", timeout=1)
    response.raise_for_status()
except requests.exceptions.Timeout:
    print("タイムアウト発生")
except requests.exceptions.HTTPError as e:
    print("HTTPエラー:", e.response.status_code)
except requests.exceptions.RequestException as e:
    print("その他のエラー:", e)
スクロールできます
種類よく使うケース
Timeout応答が遅すぎるときに検知してリトライ
ConnectionErrorサーバーに接続できないとき
HTTPErrorステータスコードで異常を検出
RequestExceptionすべての例外を一括でハンドリング
よく使う例外まとめ

本格的にエンジニアへのキャリアチェンジを考えてる人へ

プログラミングスキルを社内やプライベートで活用している人が増えています。

▼プログラミングスキルの活用事例
  • 一部業務プロセスの効率化/自動化
  • 分析システム構築による担当業務改善
  • 社内公開によるチーム/プロジェクトの業務時間短縮

Pythonは特にデータ収集や分析に特化したライブラリが豊富なため、業務プロセスの一元管理やDX化に貢献しています。

また、プログラミングに触れてエンジニアへのキャリアチェンジを実現したい人の人材規模も年々高まっています。

一度、あなたのキャリアプランを振り返ってみてください。

▼現在の状況を考える質問
  • 収入アップが見込めている
  • キャリアアップが見込めている
  • 働き方を明確に決めれている

上記の項目をYESと答えられる人は、特に言うことはありません。

現在、エンジニアへのキャリアチェンジでお悩みの方は、「【Python特化】厳選したおすすめプログラミングスクール」を一読ください。

本格的にエンジニアへのキャリアチェンジを考えてる人へ、Python特化の厳選したプログラミングスクールを解説してます。
また、スクールのメリットや金額など学習プラン設計についても言及してます。

この記事を書いた人

sugiのアバター sugi SUGI

【経歴】玉川大学工学部卒業→新卒SIer企業入社→2年半後に独立→プログラミングスクール運営/受託案件→フリーランスエンジニア&SEOコンサル→Python特化のコンテンツサイトJob Code運営中

目次