How to Scrape Websites That Require a Login (2026 Guide)

Log in with Python Requests and CSRF tokens, reuse sessions with Playwright storage state, refresh API tokens, and keep the account safe. All code tested.

Author
ProxyHorizon Team
Published
November 27, 2026
16 min read
Expert-Verified
How to Scrape Websites That Require a Login (2026 Guide)

The data you want is often one login away. Order histories, member-only prices, dashboards, your own analytics: none of it shows up for an anonymous visitor, so a plain scraper sees nothing.

Scraping behind a login isn’t magic. A website remembers you with a cookie or a token, and your scraper just needs to get one and send it back on every request. The hard parts are the details: CSRF tokens, expired sessions, JavaScript login forms, two-factor prompts and keeping the account from getting flagged.

This guide walks through all of it with Python code we ran against a public practice site and a small local API. You’ll see the exact output, including what happens when a token is missing.

TL;DR
  • A login gives you a cookie or token; your scraper must send it back every time.
  • Load the login page first to grab the CSRF token, or the login silently fails.
  • Use Playwright’s storage_state to log in once and reuse the session.
  • Check each page for a logged-in marker and re-login when it disappears.
  • Use your own accounts, one sticky IP per session, and never try to beat 2FA.

First, Make Sure You’re Allowed to Do This

Logging in changes the legal picture. Public pages are one thing; an account means you’ve agreed to the site’s terms.

When you create an account, you accept the site’s terms of service. Many of them ban automated access outright. Breaking those terms can get the account closed, and in some cases it can support a legal claim against you. Scraping public pages without logging in usually sits on firmer ground.

A few rules keep you on the safe side:

  • Only use accounts you own or have written permission to use. Never use someone else’s credentials.
  • Read the terms and check for an official API or data export first. Many services let you download your own data.
  • Avoid personal data about other people unless you have a lawful reason to process it. Privacy laws like the GDPR apply even when the page is behind your own login.
  • Never bypass access controls you aren’t entitled to pass, such as paywalls on content you haven’t paid for.

Our guide to web scraping legality and robots.txt covers the wider rules. This isn’t legal advice, so talk to a lawyer before scraping logged-in data for a commercial project.

How Website Logins Actually Work

Almost every login ends the same way: the server hands you a credential, and your browser sends it back on every request after that. What differs is the type of credential and how hard it is to get.

HTTP itself has no memory. Each request stands alone, so the site needs a way to recognize you. That’s why a logged-in scraper is a stateful scraper. Our post on stateless vs stateful scraping explains why that changes how you design the whole job.

Login typeWhat the site gives youBest scraping approach
Classic HTML formA session cookieRequests session with the CSRF token
JavaScript login pageA cookie or a token in localStoragePlaywright, then save the storage state
API-backed single-page appA bearer token (often a JWT)Call the JSON API with an Authorization header
SSO (Google, Microsoft, Okta)A cookie after several redirectsLog in once in a real browser, reuse the state
Two-factor authenticationA cookie, after a code or promptLog in by hand once, reuse the state

1Session Cookies

On a classic site, you submit a username and password. The server checks them, creates a session, and replies with a Set-Cookie header. Your browser stores that cookie and attaches it to every later request to the same site. When the cookie expires or you log out, the session ends.

2CSRF Tokens

Most login forms include a hidden field with a random value, called a CSRF (cross-site request forgery) token. The server issues it with the login page and rejects any login that doesn’t send it back. It stops other sites from submitting forms in your name, and it’s the most common reason a naive login script fails.

3Bearer Tokens

Modern apps built in React or Vue often skip cookies for data. The login call returns an access token, and the app sends it in an Authorization: Bearer header with every API request. These tokens usually expire within minutes or hours, so your scraper has to refresh them.

Diagram of a website login flow: get the login page with a CSRF token, post credentials, receive a session cookie, then request protected pages
The login handshake your scraper has to repeat: get the form, send the token back, keep the cookie.

Step 1: Inspect the Login in Your Browser’s DevTools

Before writing any code, watch a real login happen. Five minutes in DevTools saves hours of guessing.

  1. Open the login page and press F12 to open DevTools. Go to the Network tab.
  2. Tick Preserve log, so the requests don’t vanish when the page redirects after login.
  3. Log in normally with your own account.
  4. Find the request sent when you clicked the button. It’s usually a POST to a path like /login, /session or /api/auth.
  5. Open its Payload tab. Note every field name, including hidden ones like csrf_token or authenticity_token.
  6. Open the Response Headers and look for Set-Cookie, or check the response body for an access_token.

This tells you which method you need. A form post with a cookie in the reply points to Requests. A JSON post that returns a token points to the API route. If the request is buried in obfuscated JavaScript or protected by a challenge, go straight to Playwright.

Also note the request headers the browser sent. Some sites check the Referer, Origin or User-Agent on login. Our guide to HTTP headers for web scraping covers which ones matter.

Step 2: Log In With Python Requests

For a classic form login, a requests.Session does almost all the work. It stores cookies from each response and sends them back automatically.

We tested this against Quotes to Scrape, a public practice site built for scraping tutorials. Its login form has a hidden CSRF token and accepts any username and password. Once you’re logged in, each quote shows an extra Goodreads link, which makes it easy to prove the session works.

Python
import requests
from bs4 import BeautifulSoup

BASE = "https://quotes.toscrape.com"
USER, PASSWORD = "demo_user", "demo_pass"  # load real credentials from env vars

def login(session):
    # 1. Load the login page to get cookies and the hidden CSRF token
    page = session.get(f"{BASE}/login", timeout=15)
    soup = BeautifulSoup(page.content, "html.parser")
    token = soup.select_one("input[name=csrf_token]")["value"]
    # 2. Post the form exactly like the browser does
    resp = session.post(f"{BASE}/login", timeout=15, data={
        "csrf_token": token, "username": USER, "password": PASSWORD})
    return "Logout" in resp.text

def is_logged_in(html):
    return "/logout" in html

def get(session, url):
    resp = session.get(url, timeout=15)
    if not is_logged_in(resp.text):          # session expired or cookie lost
        print("  session lost, logging in again")
        login(session)
        resp = session.get(url, timeout=15)
    return resp

with requests.Session() as s:
    s.headers["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) Chrome/156.0 Safari/537.36"
    print("logged in:", login(s))
    print("cookies:", sorted(s.cookies.keys()))
    for n in (1, 2):
        soup = BeautifulSoup(get(s, f"{BASE}/page/{n}/").content, "html.parser")
        links = soup.select(".quote a[href*=goodreads]")
        print(f"page {n}: {len(soup.select('.quote'))} quotes, {len(links)} Goodreads links (login-only)")
    s.cookies.clear()                          # simulate an expired session
    soup = BeautifulSoup(get(s, f"{BASE}/page/3/").content, "html.parser")
    print("page 3 after re-login:", len(soup.select(".quote a[href*=goodreads]")), "Goodreads links")

Here’s what the script does, step by step:

  • GET the login page first. This sets the initial session cookie and gives you the CSRF token from the hidden input.
  • POST every field the browser sends, including the token, to the same URL the form uses.
  • Check for a logged-in marker, such as a Logout link, instead of trusting the status code.
  • Reuse the same session for every later request, so the cookie goes along each time.

The status code point matters. When we posted the form without the CSRF token, the server returned a normal 200 OK and the login page again, with the message “Error while logging in: invalid CRSF token.” (The typo is the site’s.) A script that only checks for a 200 would think it had logged in.

The anonymous version of page one showed zero Goodreads links on the quotes. The logged-in session showed ten on each page, one per quote.

Terminal output from the login scraper tests: Requests login with CSRF token, automatic re-login, Playwright saved state and a token API refresh
Real output from our test runs: a cookie login, a re-login after the session was cleared, a saved Playwright state and a token refresh.

Step 3: Detect Expired Sessions and Log In Again

Sessions don’t last forever. A scraper that runs for hours will eventually get logged out, and it needs to notice.

Sites end sessions for many reasons: a fixed timeout, inactivity, a server restart, or a security rule that kicks you out after a password change. When that happens, most sites don’t send an error. They redirect you to the login page or show the logged-out version of the page with a 200.

That’s why the get() helper in the script checks every response for a logged-in marker. If the marker is missing, it logs in once more and retries. We tested this by clearing the cookie jar mid-run. The script printed “session lost, logging in again” and page three still came back with all ten member-only links.

Pick a marker that only appears when you’re logged in. Good choices are a Logout link, your username in the header, or an account menu. Don’t rely on the URL alone, because some sites show the login form at the same address as the page you asked for.

Limit re-logins too. If a login fails twice in a row, stop and alert yourself. Repeated failed logins are one of the fastest ways to get an account locked.

Step 4: Use Playwright for JavaScript Logins

When the login runs through JavaScript, a real browser is often easier than reverse-engineering the requests. Playwright can log in once and save the result.

Many sites build the login request in JavaScript, add signed headers, or run bot checks before the form submits. Copying that in Requests is slow and breaks often. Playwright drives a real Chromium, Firefox or WebKit browser, so the site’s own code does the hard part. If you’re new to it, start with our Playwright web scraping guide.

The key feature is storage_state. After logging in, it saves the browser context’s cookies and localStorage to a JSON file. A new context created from that file starts already logged in, with no form and no password.

Python
import os
from playwright.sync_api import sync_playwright

BASE = "https://quotes.toscrape.com"
STATE = "state.json"

with sync_playwright() as p:
    browser = p.chromium.launch(headless=True)

    if not os.path.exists(STATE):
        # Run 1: log in through the real form, then save cookies + localStorage
        ctx = browser.new_context()
        page = ctx.new_page()
        page.goto(f"{BASE}/login")
        page.fill("#username", "demo_user")
        page.fill("#password", "demo_pass")
        page.click("input[type=submit]")
        page.wait_for_selector("a[href='/logout']")
        ctx.storage_state(path=STATE)
        print("logged in and saved", STATE)
        ctx.close()

    # Run 2+: start already logged in, no form, no password
    ctx = browser.new_context(storage_state=STATE)
    page = ctx.new_page()
    page.goto(f"{BASE}/page/2/")
    print("logged in:", page.locator("a[href='/logout']").count() == 1)
    print("Goodreads links:", page.locator(".quote a[href*=goodreads]").count())
    browser.close()

We ran it twice. The first run filled the form, saved state.json and reached page two logged in. The second run skipped the login completely, loaded the saved state, and still saw the Logout link and all ten member-only links.

A few details from the Playwright authentication docs are worth knowing:

  • IndexedDB isn’t saved by default. If a site keeps its auth token there (Firebase Authentication does), pass indexed_db=True when you save the state.
  • sessionStorage isn’t saved at all. If a site keeps login data there, you have to copy it yourself with an init script.
  • The state file is a live credential. Playwright warns that it can be used to impersonate you, so keep it out of Git.

Our saved file held one cookie named session, marked HttpOnly, with no expiry date. That means it’s a browser-session cookie, and the server decides when it stops working.

Step 5: Hand Browser Cookies to Requests for Speed

The fastest setup for many jobs is hybrid: log in with Playwright, then scrape with Requests using the same cookies.

A browser is slow and heavy. Each page costs hundreds of megabytes of memory and seconds of rendering. Requests fetches HTML in a fraction of that. If the pages behind the login are plain HTML, you only need the browser for the login itself.

Python
import json
import requests
from bs4 import BeautifulSoup

state = json.load(open("state.json"))
s = requests.Session()
for c in state["cookies"]:
    s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c["path"])

html = s.get("https://quotes.toscrape.com/page/4/", timeout=15).content
soup = BeautifulSoup(html, "html.parser")
print("logged in via browser cookies:", soup.select_one("a[href='/logout']") is not None)
print("Goodreads links:", len(soup.select(".quote a[href*=goodreads]")))

We loaded the cookies from state.json into a fresh Requests session and fetched page four. It came back logged in, with all ten member-only links. The browser was never opened.

This doesn’t always work. Some sites tie the session to the browser’s fingerprint or TLS signature, and reject the same cookie from a different client. If the hybrid request gets logged out, send the same User-Agent as the browser first. If that fails, keep the scraping inside Playwright.

Scraping Sites That Use Tokens Instead of Cookies

For single-page apps, skip the HTML entirely. Log in to the app’s API, keep the token, and refresh it when it expires.

In DevTools, these sites show a JSON POST on login and then a stream of fetch or XHR calls that return JSON data. Those calls are usually the cleanest data source on the site. You get structured fields without parsing any HTML.

We built a tiny local API to test this pattern. It issues a token that expires after two seconds, so we could watch the refresh happen. The client logs in, sets the Authorization header on its session, and logs in again once when it gets a 401.

Python
import sys, time
import requests

API = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8000"

class ApiClient:
    def __init__(self, username, password):
        self.s = requests.Session()
        self.creds = {"username": username, "password": password}
        self.login()

    def login(self):
        r = self.s.post(f"{API}/api/login", json=self.creds, timeout=10)
        r.raise_for_status()
        self.s.headers["Authorization"] = f"Bearer {r.json()['access_token']}"

    def get(self, path):
        r = self.s.get(f"{API}{path}", timeout=10)
        if r.status_code == 401:          # token expired: log in once more, retry once
            print("  401, refreshing token")
            self.login()
            r = self.s.get(f"{API}{path}", timeout=10)
        r.raise_for_status()
        return r.json()

api = ApiClient("demo_user", "demo_pass")
print("call 1:", api.get("/api/orders"))
time.sleep(2.5)                           # let the token expire
print("call 2:", api.get("/api/orders"))
print("no token:", requests.get(f"{API}/api/orders", timeout=10).status_code)

The first call returned the orders. After a 2.5-second pause, the second call hit a 401, refreshed the token and returned the orders again. A request without any token got a flat 401.

Real APIs often return a separate refresh_token alongside the access token. If they do, call the refresh endpoint instead of sending your password again. It’s quieter, and it’s what the site’s own app does.

What About 2FA, CAPTCHAs and SSO?

These are the walls that are meant to stop automation. The honest answer is to log in by hand once and reuse the session, not to defeat them.

1Two-Factor Authentication

If your own account uses an SMS code, a push prompt or a hardware key, your script can’t complete that step on its own, and it shouldn’t try. Run Playwright with headless=False, log in yourself, approve the prompt, and save the storage state. Your scraper then reuses that state until it expires.

Some people automate authenticator-app codes for their own accounts with a library like pyotp, by storing the TOTP secret. That works technically, but it puts your second factor in the same place as your password, which removes most of its value. Do it only for dedicated test accounts.

2CAPTCHAs on the Login Form

A CAPTCHA on the login page means the site is actively screening bots there. Logging in by hand and reusing the state avoids triggering it on every run. Our guide to handling CAPTCHAs in web scraping explains why they appear and how to reduce them, without breaking the rules.

3Single Sign-On

“Sign in with Google” and company SSO bounce you through several domains before you land back on the site. Scripting that with Requests is fragile. Log in once in a headed Playwright browser and save the state. You’ll get the final site’s cookies, which are all your scraper needs.

Keep the Account Safe: Proxies, Pace and Sessions

Once you’re logged in, every request is tied to a named account. The site doesn’t need to fingerprint you anymore: it already knows who you are.

That changes how you should use proxies. On public pages, rotating IPs spreads requests out. On a logged-in session, an account that jumps between countries every few seconds looks like a stolen account. Many sites will log you out or lock the account for that.

  • Keep one IP per session. Use a sticky proxy session that holds the same IP for the life of the login. Our guide to sticky vs rotating proxy sessions explains the trade-off, and our proxy provider directory shows which services offer sticky sessions.
  • Match the account’s usual location. An account normally used from India shouldn’t suddenly appear from Brazil.
  • Set the proxy on the session, so the login and every later request use the same exit IP. See how to use proxies with Python Requests.
  • Scrape slower than you would anonymously. Logged-in limits are often stricter, and the cost of hitting them is the account. Our rate limiting guide covers safe pacing.

Run one account per session and don’t share cookies between parallel workers unless the site clearly allows concurrent use. Ten threads hammering one session is an obvious bot pattern.

Store Credentials and Sessions Securely

A login scraper holds keys to a real account. Treat its secrets the way you’d treat your own password.

  • Never hardcode passwords. Load them from environment variables or a secrets manager. Our examples use placeholder values for that reason.
  • Protect the session files. A state.json or a pickled cookie jar works like a password until it expires. Add them to .gitignore and restrict file permissions.
  • Use a dedicated account where possible, so a ban or a leak doesn’t take your main account with it.
  • Log out when the job ends if the site supports it. That kills the session on the server, so a leaked file stops working.
Decision guide for choosing a login scraping method: Requests for form logins, Playwright for JavaScript logins, the API route for token logins, and a manual login for 2FA
Match the method to the login: a form, a JavaScript page, a token API, or a manual step you can’t automate.

Troubleshooting a Login Scraper

Most login scrapers fail for one of a handful of reasons. Check these in order.

  • The login “succeeds” but pages are logged out. You’re probably missing the CSRF token or another hidden field. Compare your POST with the one in DevTools field by field.
  • The cookie isn’t being sent. Make sure you use one Session object for everything. Separate requests.get() calls don’t share cookies.
  • It worked yesterday and fails today. The session or the saved state expired. Delete the state file and log in fresh.
  • You get a 403 on the login POST. The site may check the Origin or Referer header, or block your client. Copy the browser’s headers, or switch to Playwright.
  • Garbled characters in the HTML. Parse response.content instead of response.text, so Beautiful Soup can read the page’s own encoding.
  • The account gets logged out or locked. Slow down, stick to one IP, and stop retrying failed logins automatically.

Frequently Asked Questions

Final Thoughts

Scraping behind a login comes down to three jobs: get the credential, send it back every time, and notice when it stops working. For classic forms, a Requests session with the CSRF token does it in a few lines.

For JavaScript logins, Playwright and a saved storage state do the heavy lifting, and you can hand the cookies to Requests for speed.

The harder questions aren’t technical. Use your own accounts, respect the terms, keep the session on one steady IP, and never try to beat 2FA or CAPTCHAs. Do that, and a logged-in scraper is one of the most reliable kinds you can build.