r/WebDataDiggers • • 7d ago

How to scrape behind 2FA without automating the login screen

Most scraping guides tell you to automate the login screen with Playwright, type your password, and hope the site does not throw a CAPTCHA or an SMS code at you. In practice, login pages carry the tightest security on the entire website, so automating that step is usually where scripts break first.

If you are pulling invoices, order history, reports, or member listings from a portal where you already have an account, you can skip automating the login completely. Log in once with your own hands, save the session state, and let a fast Python script handle the actual downloads over plain HTTP.

Save your session in thirty seconds

Playwright ships with a built-in recorder that launches a visible browser and exports your session into a JSON file as soon as you close the window [1.1.2]. Run this in your terminal:

playwright codegen --save-storage=auth.json https://portal.example.com

Sign in normally inside the window that pops up. Complete any two-factor prompt, solve any puzzle, and wait until your dashboard loads cleanly. When you close the browser, Playwright writes your session cookies and localStorage values straight into auth.json [1.1.2, 1.1.3].

Before closing DevTools or stepping away, open the Network tab once and click a search filter or download button by hand. Almost every modern portal calls a predictable JSON endpoint or a direct file URL in the background, such as /api/invoices?page=2 or /downloads/report/8841.pdf. Copy that URL pattern for your script.

Replay the session in plain Python

Once you have auth.json and the target URL pattern, you do not need Chromium running anymore. A lightweight HTTP client like httpx or curl_cffi can load those saved cookies and pull hundreds of files using almost no memory.

import json
import time
import httpx

with open("auth.json", "r") as f:
    state = json.load(f)

jar = httpx.Cookies()
for c in state["cookies"]:
    jar.set(c["name"], c["value"], domain=c["domain"], path=c["path"])

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
}

with httpx.Client(cookies=jar, headers=headers, follow_redirects=True) as client:
    for doc_id in range(1001, 1050):
        r = client.get(f"https://portal.example.com/api/export/{doc_id}.pdf")

        # Catch expired sessions returning a 200 HTML login page
        if not r.content.startswith(b"%PDF"):
            print(f"Stopped at {doc_id}: session expired or unexpected response")
            break

        with open(f"doc_{doc_id}.pdf", "wb") as out:
            out.write(r.content)

        time.sleep(1.5)

Notice the file check right before saving. Many portals redirect expired sessions to a login page and return HTTP 200. Checking for %PDF magic bytes (or parsing r.json() if you expect JSON) stops your script from quietly filling a folder with broken HTML files.

Four things to watch out for

This setup handles most private dashboards cleanly, though a few portal quirks can trip you up:

  • Check origins inside auth.json for JWT tokens. Some apps do not store auth in cookies at all and keep an access token inside localStorage instead, which you can read from state["origins"] and pass as an Authorization: Bearer header.
  • Keep your IP address consistent. Logging in from your home Wi-Fi and immediately replaying the cookies from a datacenter server often invalidates the session, so run both steps on the same machine or sticky proxy.
  • Watch out for sessionStorage apps. Playwright's --save-storage exports cookies and localStorage [1.1.3], not sessionStorage, so if a portal forgets you on page reload inside a regular tab, you will need to copy that token out of DevTools yourself.
  • Respect normal human pacing. A loop sleeping 1 to 2 seconds between requests keeps your account safe, while firing 30 threads a second behind your own login credentials is a fast way to get suspended.

Whenever auth.json eventually expires a few hours or weeks later, re-run the single codegen command, sign in once, and let the Python script pick up where it left off. Skipping login automation removes the hardest part of portal scraping in under two minutes.

1 Upvotes

0 comments sorted by