Pythonで利用されるHTTPライブラリのrequestsに関する解説になります。
以下の内容をまとめています。
- requestsモジュールとは何か
- requestsとSeleniumの違い
- requestsのインストール
- requestsの使い方
- requests.get()の引数の使い方
- responseオブジェクトの確認
- SIer/Web系企業での実務経験があるフリーランスエンジニア
- プログラミングスクールでの講師実績あり
- HR領域によるエンジニア特化の採用代行を業務委託で兼務
【無料配布】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は、特にWebスクレイピングに利用されたり、WebAPI連携によるデータ取得などに利用されます。
requestsとSeleniumの違い
requestsとSeleniumの違いは、ブラウザ操作・制御の有無になります。

requestsは、Seleniumと違ってブラウザ操作を実施しないため、URLをもとにサイト情報を取得します。
また、サイト情報をHTMLあるいはXMLなどのデータで取得するため、取得後はBeautifulSoupといった解析用ライブラリを利用する必要があります。
Seleniumにおける各メソッドの使い方を詳細に知りたい人は、「【業務自動化】Seleniumとは?インストールから使い方まで徹底解説!」を一読ください。

requestsのインストール
requestsはサードパーティライブラリであるため、別途インストールが必要になります。
.pyファイルにコードを記述する前にrequestsをインストールしておきましょう。
pip install requests
Macならターミナル、Windowsであればコマンドプロンプトで実施後、Successfullyが表示されたら完了です。
requestsのメソッドの使い方
改めて、代表的なrequestsのメソッドは以下の4つです。
メソッド名 | 説明 |
---|---|
requests.get() | サーバーから情報を取得 |
requests.post() | サーバーへ情報を送信 |
requests.put() | サーバーの情報を更新 |
requests.delete() | サーバーの情報を削除 |
本記事では、Webスクレイピングを利用するため、.get()メソッドを重点的に解説します。
ログインが必要なケースで.session()メソッドを利用する場合があるため、ログイン処理を含めた解説は後述します。
requests.get()の引数の使い方
Webスクレイピングといったデータ収集などで頻繁に利用されるのがrequests.get()になります。
res = requests.get(URL, 任意の引数)
.get()メソッドを利用することで直感的に操作することができます。
また、以下が主な引数になります。
メソッド名 | 必須/任意 | 説明 |
---|---|---|
URL | 必須 | 対象URL |
headers | 任意 | リクエスト時にヘッダーデータを辞書で指定 |
params | 任意 | リクエスト時にURLのクエリパラメータを辞書で指定 |
cookies | 任意 | リクエスト時にクッキーを辞書で指定 |
timeout | 任意 | リクエスト時のタイムアウトを指定 |
スクレイピング業務では、引数にURLのみを利用することが多いです。
requests.get()によるresponseオブジェクトの確認
リクエスト後の戻り値(応答)として、responseオブジェクトが返ってきます。
以下がresponseオブジェクトの属性値になります。
属性 | 説明 |
---|---|
status_code | ステータスコード |
headers | レスポンスヘッダーのデータ |
content | レスポンスのバイナリデータ |
text | レスポンスのテキストデータ |
encoding | エンコーディング(変換方式:utf-8など) |
cookies | クッキーデータ |
ここでは、以下の条件でresponseオブジェクトがどのようなデータを返すか確認します。
引数 | データ |
---|---|
URL | https://google.co.jp/ |
params | {‘q’:’Python’} |
上記の引数をrequests.get()メソッドに渡します。
import requests
url = 'https://google.co.jp'
params = {'q':'Python'}
response = requests.get(url, params=params)
responseオブジェクトの各属性を確認します。
レスポンスデータの解析を理解したい人は、「【チートシート】BeautifulSoup4とは?インストールから使い方まで徹底解説!」を一読ください。

status_code(ステータスコード)
HTTPステータスコードは、サーバー側からのレスポンスの状況を確認するコードになります。
3桁が連なったコードであり、何番台かによって状況が異なります。
ステータスコードを理解することで、エラー処理などに役立ちます。
ステータスコード | 範囲 | 説明 |
---|---|---|
100~ | 100~199 | Informational:リクエストは受信されて処理が継続する |
200~ | 200~299 | Success:リクエストが成功している |
300~ | 300~399 | Redirection :リダイレクトや遷移などリクエスト完了に追加処理が必要になる |
400~ | 400~499 | Client Error:クライアントからのリクエストに誤りがある |
500~ | 500~599 | Server 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, cert | HTTP GETリクエストを送信します |
post() | url, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, stream, verify, cert | HTTP POSTリクエストを送信します |
put() | url, data, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, cert | HTTP PUTリクエストを送信します |
delete() | url, headers, cookies, auth, timeout, allow_redirects, proxies, stream, verify, cert | HTTP 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, cert | HTTP PATCHリクエスト(部分更新)を送信します |
request() | method, url, params, data, json, headers, cookies, files, auth, timeout, allow_redirects, proxies, stream, verify, cert | 任意のHTTPメソッドでリクエストを送信します(上記各関数の汎用版) |
関数/オブジェクト | 説明 |
---|---|
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 | クエリパラメータ(辞書やタプル形式で渡す) |
headers | HTTPヘッダー情報(辞書) |
cookies | クッキー情報(辞書) |
auth | 認証情報(例:(ユーザー名, パスワード)) |
timeout | タイムアウト時間(秒単位) |
allow_redirects | リダイレクトの許可(デフォルトはTrue) |
proxies | プロキシ設定(辞書形式) |
stream | レスポンスをストリーミングで受け取る(大きなファイルなど) |
verify | SSL証明書の検証(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 | フォームデータやバイナリデータなど(辞書・タプル・文字列・ファイルなど) |
json | JSON形式のデータ(Pythonの辞書で渡すと自動的にJSONに変換される) |
headers | HTTPヘッダー情報(例: Content-Type, Authorization など) |
cookies | クッキー情報(辞書) |
files | ファイル送信に使うデータ(辞書形式でファイルオブジェクトを渡す) |
auth | 認証情報(例: (ユーザー名, パスワード)) |
timeout | タイムアウト時間(秒数) |
allow_redirects | リダイレクトの許可(デフォルトはTrue) |
proxies | プロキシ設定(例: {‘http’: ‘http://proxy.example.com:8080’}) |
stream | レスポンスをストリーミングで受信する(True/False) |
verify | SSL証明書の検証(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 | 更新するデータ(辞書・タプル・文字列・ファイルなど) |
json | JSON形式のデータ(Pythonの辞書など) |
headers | HTTPヘッダー情報(例: Content-Type, Authorization など) |
cookies | クッキー情報(辞書) |
files | ファイル送信に使うデータ(辞書形式でファイルオブジェクトを渡す) |
auth | 認証情報(例: (ユーザー名, パスワード)) |
timeout | タイムアウト時間(秒数) |
allow_redirects | リダイレクトの許可(デフォルトはTrue) |
proxies | プロキシ設定(辞書形式) |
stream | レスポンスをストリーミングで受信する(True/False) |
verify | SSL証明書の検証(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(必須) |
params | URLクエリパラメータ(辞書やタプル) |
headers | HTTPヘッダー情報 |
cookies | クッキー情報(辞書) |
auth | 認証情報(例: (ユーザー名, パスワード)) |
timeout | タイムアウト時間(秒) |
allow_redirects | リダイレクトを許可するか(デフォルトは True) |
proxies | プロキシ設定(辞書形式) |
stream | レスポンスをストリーミングで受け取る(True/False) |
verify | SSL証明書を検証するか |
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) |
verify | SSL証明書を検証するか |
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 | クエリパラメータ(辞書やタプル) |
headers | HTTPリクエストヘッダー |
cookies | クッキー情報(辞書) |
auth | 認証情報(例: (ユーザー名, パスワード)) |
timeout | タイムアウト時間(秒) |
allow_redirects | リダイレクトの許可(デフォルトは True) |
proxies | プロキシ設定(辞書形式) |
stream | レスポンスをストリーミングで受け取る(True/False) |
verify | SSL証明書を検証するか |
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) |
json | JSONデータ(Pythonの辞書を自動的にJSONに変換) |
headers | リクエストヘッダー |
cookies | クッキー情報(辞書) |
auth | ベーシック認証 (ユーザー名, パスワード) |
params | クエリパラメータ |
timeout | タイムアウト秒数 |
allow_redirects | リダイレクトの許可(デフォルトは True) |
proxies | プロキシサーバの設定 |
stream | レスポンスをストリーミングで取得 |
verify | SSL証明書の検証 |
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) |
json | JSON形式で送信するデータ(辞書を指定) |
headers | HTTPヘッダー(辞書形式) |
cookies | クッキーの送信(辞書形式) |
files | ファイルのアップロード用データ(例:{‘file’: open(‘file.txt’, ‘rb’)}) |
auth | ベーシック認証((ユーザー名, パスワード)) |
timeout | タイムアウト秒数 |
allow_redirects | リダイレクトを許可するか(デフォルト:True) |
proxies | プロキシの指定 |
stream | ストリーミングで受信するか |
verify | SSL証明書の検証 |
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.cookies | Cookieの自動管理・手動設定 |
Session.params | 共通クエリパラメータを設定 |
Session.proxies | プロキシの設定 |
Session.verify | SSL検証を一括で設定 |
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 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 などを一括管理できる |
requests.Request()
requests.Request()は、リクエスト内容を手動で構成する低レベルAPIです。
このオブジェクトは.prepare()を使ってPreparedRequestに変換し、Session.send()に渡すことでHTTPリクエストを送信します。
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)
引数名 | 説明 |
---|---|
method | HTTPメソッド(’GET’, ‘POST’, など)※必須 |
url | リクエストURL(必須) |
headers | リクエストヘッダー(辞書形式) |
files | アップロードファイル({‘file’: file_obj}) |
data | フォームデータやペイロード(application/x-www-form-urlencoded) |
json | JSON形式データ(辞書形式) |
params | クエリパラメータ(URL末尾の ?key=value) |
auth | 認証情報(例:(‘user’, ‘pass’)) |
cookies | クッキー情報(辞書形式) |
hooks | レスポンスフック |
headers | HTTPヘッダーの指定 |
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()で送信します。
- 低レベルでリクエストを手動で構築・調整したいとき
- 再送信やログ出力のために完全なリクエスト情報を確認・保持したいとき
属性名 | 説明 |
---|---|
method | HTTPメソッド(’GET’、’POST’ など) |
url | 最終的に構築されたURL(クエリ含む) |
headers | 実際に送信されるヘッダー(辞書) |
body | リクエストボディ(エンコード済み) |
cookies | Cookieヘッダーに含まれる情報 |
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_code | HTTPステータスコード(例: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 | すべての例外の基底クラス(親クラス) |
HTTPError | HTTPエラー(ステータスコードが 4xx, 5xx のとき) |
ConnectionError | ネットワーク接続エラー(DNS失敗、接続タイムアウトなど) |
Timeout | タイムアウト(接続や応答に時間がかかりすぎた場合) |
ConnectTimeout | 接続タイムアウト(接続確立時に発生) |
ReadTimeout | サーバーからの応答待ちでタイムアウト |
TooManyRedirects | リダイレクトが多すぎるとき |
URLRequired | URLが不正または指定されていないとき |
MissingSchema | URLスキーマ(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特化】厳選したおすすめプログラミングスクール」を一読ください。
