セッションと Cookie の管理
セッション、Cookie、トークンを使ってリクエスト間の状態を Bot が維持し、認証が必要な複数ステップのワークフローを実行する方法を学びます。
「セッションと Cookie の管理」はCoddyKit上の無料Web Scraping & Botsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはWeb Scraping & Bots学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Web Scraping & Botsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
HTTP Is Stateless
Each HTTP request is independent: the server forgets you between calls. To build multi-step workflows, a bot must carry state itself.
Cookies and sessions are how that state travels between requests.
What a Cookie Is
A cookie is a small key-value pair the server sets via a Set-Cookie header. The client returns it on every subsequent request, letting the server recognize the same client.
Set-Cookie: session_id=abc123; Path=/; HttpOnlySession Objects
The requests.Session object automatically stores and resends cookies across requests, so a login persists for the rest of your workflow.
import requests
session = requests.Session()
session.post('https://site.com/login', data={'user': 'a', 'pass': 'b'})
# cookies now persist on subsequent calls
profile = session.get('https://site.com/profile')Inspecting Cookies
You can read what cookies a session holds. This helps debug why an authenticated request unexpectedly redirects to a login page.
for c in session.cookies:
print(c.name, '=', c.value)Setting Cookies Manually
Sometimes you obtain a cookie elsewhere (a browser export) and inject it into your session to skip the login step.
session.cookies.set('session_id', 'abc123', domain='site.com')CSRF Tokens
Forms often embed a hidden CSRF token that must be sent back on submit. Scrape it from the page first, then include it in your POST.
page = session.get('https://site.com/form')
token = extract_hidden(page.text, 'csrf_token')
session.post('https://site.com/form', data={'csrf_token': token, 'msg': 'hi'})Bearer Tokens
API-driven sites issue a token after login that you send in an Authorization header rather than as a cookie. Store it and attach it to every call.
token = login_resp.json()['access_token']
session.headers.update({'Authorization': 'Bearer ' + token})Persisting Sessions to Disk
To resume a workflow later without re-authenticating, serialize the cookie jar and reload it on the next run.
import pickle
with open('cookies.pkl', 'wb') as f:
pickle.dump(session.cookies, f)
# later
with open('cookies.pkl', 'rb') as f:
session.cookies.update(pickle.load(f))Handling Expiry
Sessions and tokens expire. Detect a redirect to login or a 401 response, then re-authenticate transparently before retrying the original request.
resp = session.get(url)
if resp.status_code == 401:
relogin(session)
resp = session.get(url)Sessions in Selenium
In a browser-driven bot, Selenium manages cookies for you. You can still read or transplant them between a requests.Session and the browser to share authentication.
for c in driver.get_cookies():
session.cookies.set(c['name'], c['value'])Security of Stored Sessions
A saved cookie jar is as sensitive as a password: anyone with it can act as you. Store session files with restricted permissions and never commit them to version control.
import os
os.chmod('cookies.pkl', 0o600) # owner read/write onlyQuick Check
Test your understanding of session management.
Recap
You learned how bots maintain state: cookies, requests.Session, CSRF and bearer tokens, persisting cookies to disk, handling expiry with re-login, and sharing auth between Selenium and requests.
Managing sessions is essential for any authenticated multi-step workflow.
AI チューターと学ぶ Python — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 12
- レッスン
- 48
よくある質問
「セッションと Cookie の管理」レッスンは無料ですか?
はい。「セッションと Cookie の管理」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Web Scraping & Botsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Web Scraping & Botsコースには全4レッスンが含まれています。
「セッションと Cookie の管理」で何を学びますか?
セッション、Cookie、トークンを使ってリクエスト間の状態を Bot が維持し、認証が必要な複数ステップのワークフローを実行する方法を学びます。 ブラウザで直接実行するハンズオンコードでWeb Scraping & Botsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Web Scraping & Botsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのWeb Scraping & Botsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「セッションと Cookie の管理」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このWeb Scraping & Botsレッスンでコードを書いて実行できますか?
はい。すべてのWeb Scraping & Botsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- ユーザー認証の処理
- 複雑なユーザージャーニーの再現
- APIとの統合
- セッションと Cookie の管理