Logged Out After One Page: Fix Scraper Login Sessions
One request after login works, the next returns the sign-in page. Trace CSRF tokens, cookie jars, and session-bound IPs, and keep the login alive.
On this page
Symptom: Login Succeeds but the Second Request Gets the Sign-In Page Again
You POST credentials to the login endpoint. The response is a 302 to the dashboard. Everything looks correct. Then the very next request — the one that actually matters — comes back as a 200 with the login form embedded in the HTML. No error, no 403. The site just quietly pretends the sign-in didn’t happen.
Here is the shape of the failing code:
import requests
LOGIN_URL = "https://store.example.com/login"
DASHBOARD_URL = "https://store.example.com/dashboard"
resp = requests.post(LOGIN_URL, data={
"username": "scraper@example.com",
"password": "hunter2",
})
print(resp.status_code, resp.url)
# 200 https://store.example.com/dashboard <- looks fine
page = requests.get(DASHBOARD_URL)
print(page.status_code, "login" in page.text.lower())
# 200 True <- the sign-in page came back
The second response is a 200. That is what makes this bug so annoying to notice in logs. Your monitoring sees success statuses while every scraped page is actually the login screen. If you store raw HTML and parse later, you can burn through an entire crawl before anyone looks at the payload. We covered this class of silent failure in Your 200 OK Responses Are Actually Block Pages — an authenticated session dying mid-crawl is the same disease with a different cause.
The log excerpt tells the story. Compare what the server handed you against what you actually sent back:
--- Request 1: POST /login ---
Response headers:
Set-Cookie: sessionid=8f3a...; Path=/; HttpOnly
Set-Cookie: csrftoken=1c9d...; Path=/
--- Request 2: GET /dashboard ---
Request headers:
Cookie: <-- empty. The jar sent nothing.
Response body:
<form action="/login" method="post">...
The server issued a perfectly good session. Your client threw it away. Three things cause this: a broken cookie jar, a stale CSRF token, or a session bound to an IP you no longer have. Work through them in that order.
Check 1: Your Cookie Jar Is Not Persisting Between Requests
The most common cause is also the dumbest: you are not using a session object. Every bare requests.post() and requests.get() creates a fresh connection with a fresh, empty cookie jar. The login response sets cookies into a jar that is garbage-collected the moment the call returns. Request two starts from zero.
The broken pattern, spelled out:
# BROKEN: each call is an independent client
resp = requests.post("https://store.example.com/login", data=payload)
page = requests.get("https://store.example.com/dashboard") # no cookies sent
# FIXED: one session, one jar, shared across every request
import requests
session = requests.Session()
resp = session.post("https://store.example.com/login", data=payload)
page = session.get("https://store.example.com/dashboard")
print("login" in page.text.lower()) # False now
One line of difference. Hours of debugging.
But a Session object is not a single fix. There are several ways to sabotage it:
| Pitfall | What happens | Fix |
|---|---|---|
| New client per request | Cookies set at login are never sent again | Use one requests.Session() for the whole run |
Redirects disabled on the login POST (allow_redirects=False) | The 302 to the dashboard is where some frameworks set the session cookie; you skip it | Leave redirects on, or capture Set-Cookie from the redirect response manually |
| Cookies scoped to a subdomain mismatch | You log in on example.com, scrape on store.example.com — the cookie’s Domain attribute does not cover the subdomain (or vice versa) | Log in and scrape on the exact same host, or read the Domain= attribute in Set-Cookie and align your URLs |
| Overwriting the jar manually | session.cookies = ... or session.cookies.clear() mid-run drops the session cookie | Mutate with session.cookies.set() only, and only to add rather than replace |
The subdomain one bites people regularly. A cookie set with Domain=example.com is sent to store.example.com. A cookie set with Domain=store.example.com is not sent to example.com. And a cookie set with no Domain attribute goes only to the exact host that set it. If your login flow bounces across hosts — SSO portals love this — verify each hop preserves the jar by dumping session.cookies after every request during debugging.
Check 2: The Login Form Posts a Fresh CSRF Token You Are Not Reusing
Suppose the jar is fine. You are using a Session, cookies are flowing, and you still get bounced. Look at your login POST payload.
Most frameworks — Django, Rails, Spring, and dozens of others — embed a per-session CSRF token in the login form as a hidden input. The token is generated when you load the login page and is tied to the cookie set with that page load. If you POST a hardcoded token, a token scraped yesterday, or no token at all, the framework rejects the login. And here is the trap: many of them reject it with a 200 and a re-rendered login form, not a 403. Your scraper records “login succeeded” because the status code said so.
The login page looks like this:
<form action="/login" method="post">
<input type="hidden" name="csrf_token" value="a1b2c3d4e5f6...">
<input type="text" name="username">
<input type="password" name="password">
<button type="submit">Sign in</button>
</form>
The field name matters. csrf_token here, authenticity_token in Rails, _csrf elsewhere. Whatever the form calls it, your POST payload must use the same name.
The correct sequence is: GET the login page first, extract the token, then POST it back.
import requests
from bs4 import BeautifulSoup
session = requests.Session()
# Step 1: fetch the login page to obtain the token + its matching cookie
login_page = session.get("https://store.example.com/login")
soup = BeautifulSoup(login_page.text, "html.parser")
token = soup.find("input", {"name": "csrf_token"})["value"]
# Step 2: POST the token along with credentials
resp = session.post("https://store.example.com/login", data={
"csrf_token": token,
"username": "scraper@example.com",
"password": "hunter2",
})
The ordering is not optional. The CSRF token is validated against the csrftoken-style cookie issued with the login page GET. Fetch the page and POST the credentials through the same session, in that order, and the pair stays consistent.
A stale token fails silently in the worst way. You get a 200, the form comes back, and your scraper marches on believing it is authenticated. This is why the final fix in this post includes an explicit logged-in check on every page — don’t trust the login response alone.
Check 3: The Site Binds Your Session to an IP Address That Keeps Changing
This is the cause nobody suspects until the first two checks come up clean. Some sites store the client IP alongside the session server-side. Every request, the server compares the session’s stored IP against the source IP of the incoming request. Mismatch means the session is treated as hijacked and invalidated. You log in from IP A, the next request leaves from IP B, and the server drops you.
Three environments make this especially likely:
- Rotating proxies. If your proxy pool rotates per request, you change identity mid-session by design.
- Mobile or carrier networks. NAT rebinding can swap your public IP without warning.
- Serverless runtimes. Each invocation can egress from a different IP in the provider’s pool.
Measure it before you assume it. Add an IP echo endpoint to your loop and log the parsed value on every request:
import re
def log_exit_ip(session, label):
resp = session.get("https://store.example.com/whoami")
match = re.search(r"\b\d{1,3}(?:\.\d{1,3}){3}\b", resp.text)
ip = match.group(0) if match else "unparsed"
print(f"{label}: exit IP = {ip}")
log_exit_ip(session, "before login")
session.post("https://store.example.com/login", data=payload)
log_exit_ip(session, "after login")
session.get("https://store.example.com/dashboard")
log_exit_ip(session, "page fetch")
Parse the IP out of the response body — don’t eyeball it once and hardcode the expectation into an assertion. If those three lines print different addresses, you have found your problem.
The fix is to pin the egress IP for the entire life of the session. Locally, that means routing the Session through a single static proxy:
session.proxies = {
"http": "http://user:pass@your-proxy.example.com:8080",
"https": "http://user:pass@your-proxy.example.com:8080",
}
If you offload fetching to a scraping API, the same principle applies — keep one exit IP across the whole login-to-scrape sequence. FineData exposes this through sticky session parameters: pass the same session_id on every request in the flow, set proxy_sticky to true, and give the session a session_ttl long enough to cover the full crawl (up to 86400 seconds):
import uuid
import requests
API = "https://api.finedata.ai"
HEADERS = {"Authorization": "Bearer fd_your_api_key"}
SESSION_ID = str(uuid.uuid4()) # one ID for login + every page fetch
def fetch(url):
resp = requests.post(f"{API}/api/v1/scrape", headers=HEADERS, json={
"url": url,
"use_residential": True,
"proxy_sticky": True,
"session_id": SESSION_ID,
"session_ttl": 86400,
"formats": ["rawHtml"],
})
resp.raise_for_status()
return resp.json()
The rule that matters: rotate IPs only between full login cycles, not within one. A new identity means a new login. Treat them as a package deal. For more on why this ordering matters for multi-step flows, see Keep One Exit IP Across Multi-Step Scrape Requests.
Fix: A Single Persistent Session That Refreshes Tokens and Verifies It Is Still Logged In
Now assemble the pieces. The working pattern has three commitments: one session object, token extraction before every login, and an explicit authentication check on every page fetch. Not just the first one. Every one.
import re
import time
import requests
from bs4 import BeautifulSoup
BASE = "https://store.example.com"
CREDENTIALS = {"username": "scraper@example.com", "password": "hunter2"}
class ScraperSession:
def __init__(self):
self.session = requests.Session()
self.login_count = 0
def login(self):
"""Fetch the login page, extract the CSRF token, authenticate."""
page = self.session.get(f"{BASE}/login")
soup = BeautifulSoup(page.text, "html.parser")
token_input = soup.find("input", {"name": "csrf_token"})
payload = dict(CREDENTIALS)
if token_input:
payload["csrf_token"] = token_input["value"]
resp = self.session.post(f"{BASE}/login", data=payload)
self.login_count += 1
if self.detect_logged_out(resp):
raise RuntimeError("Login POST did not authenticate; check credentials/CSRF")
return resp
def detect_logged_out(self, resp):
"""True if the response indicates we are not authenticated."""
if resp.status_code in (401, 403):
return True
if resp.history: # followed redirects — inspect the final hop
final = resp.url.lower()
if "/login" in final or "/signin" in final:
return True
if resp.status_code == 200:
# 200 with a login form is the silent-failure signature
text_lower = resp.text.lower()
if 'action="/login"' in text_lower or "sign in to your account" in text_lower:
return True
return False
def get(self, path):
"""Fetch a page; re-authenticate once if we were bounced."""
resp = self.session.get(f"{BASE}{path}")
if self.detect_logged_out(resp):
self.login()
resp = self.session.get(f"{BASE}{path}")
return resp
Two design decisions deserve explanation.
First, detect_logged_out checks the body, not just the status. As established, the silent re-render is the common failure mode, and a 302-to-login is only visible through resp.history because requests follows redirects automatically. Checking resp.url alone on a 200 response tells you nothing.
Second, the re-login in get() happens once, then the fetch is retried once. If the second fetch still returns the login page, something structural is broken — credentials revoked, account locked, IP banned — and you want the failure to propagate, not loop. A scraper that re-logins in a tight loop will trip rate limits and get the account blocked. Fail loudly instead.
My opinionated addition: add a dashboard marker check on the first page after login. Look for a logout link, a username string, an account nav element — anything that only appears for authenticated users. It converts “probably logged in” into “verifiably logged in” for the cost of one string search.
Keep the Session Alive: Heartbeats, Expiry Windows, and Rate-Aware Re-Login
Sessions expire on idle timers, not wall-clock timers. A site with a 15-minute idle timeout will keep you logged in for six hours if you touch a page every ten minutes. It will drop you during a coffee break.
So pace your requests. A heartbeat loop that hits a cheap authenticated page on an interval keeps the session warm and detects expiry the moment it happens:
def run_with_heartbeat(scraper, poll_seconds=300):
"""Scrape pages; heartbeat every poll_seconds to keep the session alive."""
last_beat = 0.0
for url in WORK_QUEUE:
if time.time() - last_beat > poll_seconds:
probe = scraper.get("/account") # cheap authenticated page
if "login" in probe.url:
scraper.login() # expired anyway — re-authenticate
last_beat = time.time()
yield scraper.get(url)
How do you pick the interval? Measure the expiry window empirically: log in, wait, probe every minute until the session dies, and note the elapsed time. Then set the heartbeat to roughly a third of the observed lifetime. The table below maps the common windows I have run into:
| Observed session lifetime | Heartbeat interval | Re-login backoff after a failed attempt |
|---|---|---|
| 15 minutes | every 5 minutes | 30 s, double each failure, cap at 10 min |
| 1 hour | every 15 minutes | 60 s, double, cap at 15 min |
| 24 hours | every 30 minutes | 5 min, cap at 1 hour |
The backoff column matters more than people expect. When a re-login fails, hammering the login endpoint is one of the fastest ways to get the account flagged or CAPTCHA-gated. Back off, and honor any Retry-After header the server sends — the same discipline applies to login endpoints as to 429s generally, which we cover in Your Backoff Ignores Retry-After: Fix Persistent 429s.
Here is the recommendation you might disagree with: schedule re-logins proactively instead of waiting for failure. If you know the session lives 15 minutes, log in fresh every 12 minutes as part of the plan. Yes, it is more login POSTs. It is also deterministic — you avoid parsing a login page by accident, avoid writing garbage rows mid-crawl, and sidestep the heisenbug that only reproduces when the crawl pauses at the wrong moment. I would rather log in two hundred times deliberately than once reactively at 3 a.m. If the site rate-limits logins aggressively, this trade flips and reactive re-login with a good detect_logged_out becomes the right call. Measure, then choose.
Debugging Toolkit: How to Confirm Which of the Three Causes You Are Hitting
When you get bounced, run this triage in order. It takes five minutes and usually isolates the cause.
1. Inspect outgoing Cookie headers. Enable logging of request headers, or dump session.cookies after each call. If the Cookie header on the failing request is missing the sessionid the server set at login, you have a jar problem. Check the pitfall table above — it is usually a new-client-per-request bug or a subdomain scoping mismatch.
2. Look for CSRF error text in the response body. Frameworks often render a message like “Your session has expired” or “Invalid or missing CSRF token” near the login form. Also compare the csrf_token you POSTed against the one currently rendered on the login page — if they differ, you sent a stale token. Rework the login to fetch-then-POST in one session.
3. Compare client IPs across requests. Use the whoami logging from Check 3. If the exit IP changed between the login POST and the failing page fetch, the site is binding sessions to IPs. Pin one IP per login cycle.
To reproduce any of this outside your scraper — which is how you prove the site’s behavior rather than your code’s — use curl with a cookie jar file:
# Fetch the login page; save cookies to jar.txt
curl -s -c jar.txt https://store.example.com/login -o login.html
# Extract the token from the saved page
TOKEN=$(grep -o 'name="csrf_token" value="[^"]*"' login.html | sed 's/.*value="//;s/"//')
# Log in, sending the saved cookies and saving any new ones
curl -s -b jar.txt -c jar.txt \
-d "csrf_token=$TOKEN" \
-d "username=scraper@example.com" \
-d "password=hunter2" \
https://store.example.com/login -o /dev/null
# Verify: 0 means logged in, >0 means the login form is still there
curl -s -b jar.txt https://store.example.com/dashboard | grep -c 'action="/login"'
The -c flag writes cookies to the file, -b reads them back. It is the shell equivalent of a Session object, which is exactly the point: if the curl sequence works and your Python does not, the bug is in your client code. If both fail, the bug is CSRF freshness or IP binding — and the whoami check will tell you which.
Wrap-Up
A scraper that logs out after one page is failing for one of three reasons: the cookie jar is not persisting, the CSRF token is stale, or the session is bound to an IP that rotated. The diagnostic order is fixed — jar first, token second, IP third — because the first two are free to check and the third requires infrastructure changes.
The durable fix is a pattern, not a patch: one Session object for the whole run, a GET of the login page before every POST, a pinned exit IP for the life of each login, and a detect_logged_out check on every single response so silent 200-status failures stay out of your data store. Add a heartbeat scaled to the measured session lifetime, back off on failed re-logins, and the 3 a.m. page of login forms stops being a thing you debug.
Related Articles
Your Data Sits in an Iframe: Fix Extraction Across Frames
Your selector matches nothing, yet the data is visible in the browser. Here's why iframes break extraction and how to fetch frame content reliably.
TutorialYour Prices Parse as NaN: Fix Number Extraction
Scraped prices like '$1,299.00' become NaN after type conversion. Trace the parsing failure, normalize messy number formats, and fix it before load.
TutorialYour Data Sits in a Shadow Root: Pierce It for Extraction
Selectors work in DevTools but return null in your scraper? Learn why web components hide data inside shadow roots and how to pierce them.