Gestire sessioni e cookie
Impari come i bot mantengono lo stato tra le richieste usando sessioni, cookie e token per gestire workflow autenticati e articolati in più passaggi.
Gestire sessioni e cookie è una lezione Web Scraping & Bots gratuita su CoddyKit. Questa è la lezione 4 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Web Scraping & Bots, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Web Scraping & Bots include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
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.
Impara Python con un tutor IA — gratis
Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.
- Corsi
- 12
- Lezioni
- 48
Domande Frequenti
La lezione «Gestire sessioni e cookie» è gratuita?
Sì — il testo completo di «Gestire sessioni e cookie» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Web Scraping & Bots, passa a CoddyKit PRO. Il corso Web Scraping & Bots include 4 lezioni in totale.
Cosa imparerò in «Gestire sessioni e cookie»?
Impari come i bot mantengono lo stato tra le richieste usando sessioni, cookie e token per gestire workflow autenticati e articolati in più passaggi. Eserciti Web Scraping & Bots con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Web Scraping & Bots?
Non è richiesta alcuna esperienza precedente. Web Scraping & Bots su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 4 di 4.
Quanto tempo richiede la lezione «Gestire sessioni e cookie»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Web Scraping & Bots?
Sì. Ogni lezione Web Scraping & Bots include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Gestione dell'autenticazione degli utenti
- Simulazione di percorsi utente complessi
- Integrazione con le API
- Gestire sessioni e cookie