Skip to main content

Guides

Authenticated Scraping

Scrape pages behind login walls using Fetchyr

5 min read


This guide covers login flows, MFA handling, and session reuse for scraping authenticated pages.

Overview

Many sites require authentication to access their data. KLOAKD's Fetchyr module handles login flows and MFA — then passes a session artifact to evadr.fetch(), kolektr.page() or webgrph.crawl().

There are three ways to get a session artifact:

| Way | Use it when | |-----|-------------| | A login session | You have an account on the site: log in interactively, or hand over your browser's cookies | | authenticate with stored credentials (step 1) | A plain username-and-password login | | An auth-chain discovery (step 2) | The login asks for something along the way, such as an MFA code |

Log in with your own account

POST /api/v1/organizations/{org_id}/fetchyr/login-sessions makes a session from your own account. From 0.7.0 the SDKs call it with fetchyr.start_login_session (startLoginSession in TypeScript and Java, StartLoginSession in Go).

import os
from kloakd import Kloakd

client = Kloakd(api_key=os.environ["KLOAKD_API_KEY"], organization_id=os.environ["KLOAKD_ORG_ID"])

# The cookies of a session in your own browser, with that browser's user agent
login = client.fetchyr.start_login_session(
    "https://example.com/account",
    method="cookies",
    cookies=[{"name": "sid", "value": "…", "domain": ".example.com"}],
    user_agent="Mozilla/5.0 …",
)
session_artifact_id = login.session_artifact_id

With "method": "interactive" (the default) the answer is 202 with a discovery_id: poll it and send your credentials and MFA code as in step 2. Either way the session lives 8 hours and is used one request at a time, at a human pace (about one request every 8 to 15 seconds, 120 an hour at most), so plan a crawl with it accordingly. If the site signs the account out, rate-limits it or challenges it, the session is paused rather than retried: read GET …/fetchyr/sessions/{artifact_id} (client.fetchyr.get_session) and, after checking the account yourself, POST …/fetchyr/sessions/{artifact_id}/resume (client.fetchyr.resume_session). See Fetchyr for every field.

Step 1 — Create a session

from kloakd import Kloakd

client = Kloakd(api_key="sk-live-...", organization_id="your-org-id")

# Store the credentials once (encrypted on the server)...
client.fetchyr.store_credentials("acme", username="user@example.com", password="secret")

# ...then log in with them
session = client.fetchyr.authenticate("acme", target_url="https://example.com/login")
print(f"Session artifact: {session.artifact_id}")

Step 2 — Logins that need input (MFA)

authenticate logs in with stored credentials. When the login asks for something along the way, such as an MFA code, use an auth-chain discovery instead: it drives a browser to the page you want, pauses when it needs input, and ends with a session artifact.

import time

d = client.fetchyr.discover_auth_chain({"target_url": "https://example.com/dashboard"})
discovery_id = d["discovery_id"]

while True:
    st = client.fetchyr.get_auth_chain_status(discovery_id)
    if st["completed"]:
        break
    if st["waiting_for_intervention"]:
        if st["intervention_type"] == "credentials":
            client.fetchyr.resume_auth_chain_credentials(
                discovery_id, {"username": "user@example.com", "password": "secret"},
            )
        elif st["intervention_type"] == "mfa":
            code = input("MFA code: ")
            client.fetchyr.resume_auth_chain_mfa(discovery_id, {"mfa_code": code})
    time.sleep(2)

session_artifact_id = st["session_artifact_id"] if st["success"] else None

The discovery waits up to 10 minutes for each answer. See Fetchyr for the fields.

The fetch and extract routes start a discovery for you when a request made without a session lands on a login form: the API's response has auth_required: true, a discovery_id to poll the same way, and login_options listing both ways to log in. The SDK results carry auth_required and discovery_id.

Step 3 — Extract authenticated pages

data = client.kolektr.page(
    "https://example.com/dashboard",
    schema={"title": "css:h1", "content": "css:article"},
    session_artifact_id=session.artifact_id,
)
for record in data.records:
    print(record)

Step 4 — Crawl authenticated pages

Use the client.crawl() orchestrator with session_artifact_id for a one-call solution:

With a session the crawl follows sign-in, sign-up and captcha links like any other; without one it leaves them out (Sign-in and captcha pages).

result = client.crawl(
    "https://example.com/dashboard",
    max_depth=2,
    session_artifact_id=session.artifact_id,
    extract_schema={"title": "css:h1", "content": "css:article"},
)
print(f"Crawled {result.total_pages_discovered} authenticated pages")
for page in result.pages:
    print(f"  {page.url}: {page.structured_data}")

Or use the low-level webgrph.crawl() (it waits for the crawl and returns its pages):

crawl = client.webgrph.crawl(
    "https://example.com/dashboard",
    max_depth=2,
    session_artifact_id=session.artifact_id,
)
print(f"Crawled {crawl.total_pages} authenticated pages")

Session reuse

Reuse the same session_artifact_id across multiple requests; log in again when the site ends the session. A login session made from your own account lasts 8 hours and paces its requests (above):

# One login, many extractions
pages = ["/dashboard", "/profile", "/settings"]
for path in pages:
    data = client.kolektr.page(
        f"https://example.com{path}",
        schema={"title": "css:h1"},
        session_artifact_id=session.artifact_id,
    )
    print(f"{path}: {len(data.records)} records")

Tips

  • Use client.crawl() with session_artifact_id — one call handles authenticated discovery, fetching, and extraction
  • Create sessions before crawling — login once, crawl many pages
  • Check auth_required on results — the page asked for a login (it is still returned); finish the discovery_id it names, or start a login session
  • Store artifact_id for reuse — avoids re-login for subsequent jobs
  • End sessions you no longer need — client.fetchyr.terminate_session(artifact_id)

Next steps

Was this page helpful?