0Pricing
Web Scraping & Bots · 课时

管理会话与 Cookie

学习机器人如何使用会话、Cookie 和令牌跨请求维护状态,以支持经过身份验证的多步骤工作流。

管理会话与 Cookie 是 CoddyKit 上的免费 Web Scraping & Bots 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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=/; HttpOnly

Session 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 only

Quick 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.

常见问题解答

「管理会话与 Cookie」课时是免费的吗?

是的 — 「管理会话与 Cookie」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Web Scraping & Bots 课程的其余内容,请升级到 CoddyKit PRO。 Web Scraping & Bots 课程共包含 4 节课。

「管理会话与 Cookie」这节课中我会学到什么?

学习机器人如何使用会话、Cookie 和令牌跨请求维护状态,以支持经过身份验证的多步骤工作流。 你通过在浏览器中直接运行的动手代码来练习 Web Scraping & Bots,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Web Scraping & Bots 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Web Scraping & Bots 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「管理会话与 Cookie」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Web Scraping & Bots 课中编写并运行代码吗?

能。每节 Web Scraping & Bots 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 处理用户身份验证
  2. 模拟复杂用户流程
  3. 与 API 集成
  4. 管理会话与 Cookie
← 返回 Web Scraping & Bots