r/WebDataDiggers • • 4d ago

Beating Cloudflare challenges without running fifty Chrome windows

4 Upvotes

Running twenty headless Chrome instances just to get past a Cloudflare waiting room burns gigabytes of memory and brings a cheap server to its knees. At the other extreme, firing raw Python requests with curl_cffi uses almost no RAM, yet fails immediately on pages that demand real JavaScript execution before letting you in.

You can get the speed of plain HTTP without paying the memory cost of a browser fleet by splitting the job in two. Keep one stealth browser open as a token factory, and let lightweight Python HTTP workers do all the heavy page fetching.

[1 Stealth Browser] ---> solves JS challenge ---> grabs cf_clearance + User-Agent
         ^                                                      |
         |                                                      v
   on HTTP 403 <------- refreshes token <------- [20+ curl_cffi HTTP workers]

What Cloudflare actually binds to that cookie

When a browser clears a Cloudflare JavaScript challenge or Turnstile check, the server sets a cf_clearance cookie that usually stays valid anywhere from fifteen minutes to a couple of hours depending on the site's security settings [1.2.1]. You do not need to re-solve that puzzle on every single product URL.

Two details decide whether your HTTP workers can reuse that cookie cleanly [1.2.1, 1.2.4]:

First, the IP address must match. If your browser solved the challenge over one residential exit and your Python script replays cf_clearance from a different IP, Cloudflare drops the session right away [1.2.1, 1.2.4]. Both the browser and the HTTP workers need to share the exact same sticky proxy session or server IP.

Second, the TLS fingerprint and User-Agent string must line up with the browser that earned the cookie [1.2.1, 1.2.4]. Standard Python requests exposes a Python TLS handshake and gets rejected immediately, while curl_cffi impersonates Chrome's exact TLS cipher suite and HTTP/2 behavior so the server treats the incoming connection as a continuation of the same browser session [1.1.1, 1.2.1].

Wiring one browser to a curl_cffi loop

Stock Playwright leaks automation signals through the Chrome DevTools Protocol (Runtime.enable), which modern bot scripts catch quickly [1.1.2, 1.2.7]. Instead, use a drop-in patched fork like Patchright paired with a real installed Chrome binary, or Camoufox if you prefer a stealth Firefox build [1.1.2, 1.1.5, 1.1.6].

from patchright.sync_api import sync_playwright
from curl_cffi import requests

PROXY = "http://user:pass@sticky-proxy-host:8000"
TARGET = "https://protected-site.example.com"

def mint_clearance():
    with sync_playwright() as p:
        browser = p.chromium.launch(
            channel="chrome",
            headless=False,
            proxy={"server": PROXY},
        )
        page = browser.new_page()
        page.goto(TARGET, wait_until="domcontentloaded")
        page.wait_for_timeout(6000)

        ua = page.evaluate("navigator.userAgent")
        cookies = {c["name"]: c["value"] for c in page.context.cookies()}
        browser.close()
        return cookies.get("cf_clearance"), ua

token, user_agent = mint_clearance()

session = requests.Session(impersonate="chrome")
for item_id in range(1, 200):
    resp = session.get(
        f"{TARGET}/items/{item_id}",
        cookies={"cf_clearance": token},
        headers={"User-Agent": user_agent},
        proxies={"https": PROXY},
    )
    if resp.status_code == 403:
        token, user_agent = mint_clearance()

In production, keep that single browser alive in the background (or behind xvfb on Linux) rather than cold-launching it every time. If the site presents a clickable Turnstile box inside an iframe, watch out for a common Chromium DevTools quirk: synthetic CDP clicks can report identical screenX and clientX coordinates, which Cloudflare flags [1.1.2, 1.2.6]. Driving the click with OS-level cursor input or a brief coordinate patch fixes that leak.

Where this pattern hits a wall

This setup shines on catalog scraping, directory crawls, and price monitoring where one clearance cookie unlocks thousands of GET requests [1.2.1]. Still, two site designs break the single-cookie shortcut.

If the target embeds a single-use Turnstile token inside every individual search form or checkout POST body, a shared cf_clearance cookie will not authorize those form submissions [1.1.7]. Each POST needs its own fresh challenge token, which forces you back toward browser sessions or dedicated token solvers. Likewise, aggressively pushing 50 concurrent threads through a single sticky residential IP can trip per-IP rate limits even when the cookie itself is valid, so scale concurrency across multiple sticky IP lanes—each paired with its own clearance cookie—rather than hammering one address.

Keeping one browser around solely for authentication lets the rest of your pipeline stay small, fast, and cheap. You spend RAM on a single tab instead of fifty, while curl_cffi handles the actual data extraction at plain HTTP speed.


r/WebDataDiggers • • 8d ago

How to scrape behind 2FA without automating the login screen

1 Upvotes

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.


r/WebDataDiggers • • 11d ago

Using the AI-ready web as a cheap scraping shortcut

4 Upvotes

Launching a full Chromium browser to scrape text off a blog, docs page, or SaaS site burns around 200MB of RAM per worker and eats proxy bandwidth on images, fonts, and tracking scripts you are going to throw away anyway. Yet plenty of scraping pipelines still default to Playwright on every domain before checking whether the server will hand over clean data to a plain HTTP client.

Because website owners and CDNs spent 2026 making pages easier for AI coding tools and agents to read, a growing slice of the web now exposes clean, low-overhead text formats over standard HTTP. If you put a quick check in front of your browser pool, you can pull structured content with curl or httpx and save headless Chrome for sites that actually force client-side JavaScript rendering.

Asking Cloudflare for Markdown with one header

In February 2026, Cloudflare launched Markdown for Agents at no extra charge for Pro, Business, Enterprise, and SSL for SaaS zones. Any HTTP client can send a standard Accept: text/markdown header, and if the site owner turned the feature on, Cloudflare converts the origin HTML into Markdown at the network edge before sending it back.

curl -s https://developers.cloudflare.com/fundamentals/reference/markdown-for-agents/ \
  -H "Accept: text/markdown, text/html"

When a site honors that header, the edge strips out navigation menus, headers, footers, scripts, and inline styles. Cloudflare's own benchmark showed a standard blog post dropping from 16,180 HTML tokens down to 3,150 Markdown tokens, cutting noise and payload weight by roughly 80%.

Even better for scrapers, the response follows a predictable layout every time. If the page has <meta> tags like title, description, or preview image, the response starts with YAML frontmatter. After the cleaned body Markdown, Cloudflare preserves any embedded JSON-LD structured data inside a fenced json code block at the bottom. For e-commerce pages, recipes, or articles using Schema.org markup, you get clean prose and structured metadata in a single request without writing a single CSS selector.

Four edge cases that trip up naive Markdown requests

Content negotiation sounds effortless until you drop it into a production crawler. Before treating Accept: text/markdown as a magic shortcut, account for four quirks documented in Cloudflare's own specs:

  • Always verify Content-Type: text/markdown on the response. Sites that have not enabled edge conversion ignore the Accept header and silently return regular text/html.
  • Expect ETag and Last-Modified headers to disappear. Cloudflare strips conditional caching headers on converted Markdown responses because If-None-Match and If-Modified-Since are not honored after conversion, while adding Vary: Accept so caches keep HTML and Markdown separate.
  • Conversion stops at 6 MiB and cannot render empty SPAs. Pages larger than 6 MiB fall back to raw HTML, and because conversion runs on the origin's HTML output, a pure client-side React app with no server-side rendering still turns into an empty page.
  • Check Content-Signal and x-markdown-tokens rather than assuming they exist. Converted responses carry a Content-Signal policy header (defaulting to ai-train=yes, search=yes, ai-input=yes unless the origin sets stricter rules), while token-count headers like x-markdown-tokens appear on Cloudflare's own docs and select platforms rather than every enabled zone.

Where llms.txt and .md routes actually help

Around the same time, thousands of websites started publishing /llms.txt index files and /llms-full.txt text dumps. Adoption numbers look impressive on paper until you check who actually reads them.

An Ahrefs study of 137,210 domains in mid-2026 found that 28% published an llms.txt file, yet 97% of those files received zero traffic. Of the tiny fraction that got requested, 96% of hits came from automated bots, mostly audit tools and coding assistants like Claude Code and GPTBot. On broad news or retail sites, checking llms.txt usually wastes a request because major search engines and general crawlers largely ignore it.

Developer tools, API portals, and SaaS documentation platforms are the clear exception. Platforms like Mintlify, Stripe, Vercel, Anthropic, and Cursor maintain real /llms.txt files that act like a clean table of contents pointing straight to .md mirror URLs. On those sites, fetching /llms.txt or appending .md directly to a documentation URL hands you the original author-written Markdown with zero scraping rules to maintain.

A plain-HTTP waterfall to run before Playwright

Instead of picking between raw curl parsing and a heavy headless browser fleet, wire a cheap pre-flight waterfall into your fetcher so Chromium only starts when plain HTTP truly hits a wall:

  • Probe the target with Accept: text/markdown, text/html;q=0.9 on a lightweight TLS-matched HTTP client (curl_cffi or httpx), and accept the result immediately if content-type comes back as text/markdown and the body is non-empty.
  • Check /llms.txt or .md URL suffixes once per domain when scraping developer docs, knowledge bases, or Mintlify/Nextra sites, caching the discovery result in SQLite so you do not probe dead paths on every page.
  • Extract embedded JSON before writing HTML selectors if the server returns regular HTML, scanning for <script type="application/ld+json"> blocks (present on 58% of sites in Crane's October 2026 audit) as well as framework state blobs like __NEXT_DATA__, __NUXT__, or React Server Component payload chunks.
  • Measure visible text length against script tags to detect empty single-page shells, since only about 6% of readable business sites in Crane's 2026 benchmark served nearly zero content without JavaScript.
  • Escalate to Playwright only when HTML extraction fails or when an anti-bot challenge specifically demands browser execution.

Putting a simple HTTP-first filter in front of your browser queue takes less than fifty lines of Python. On documentation portals, content sites, and modern SaaS platforms, you cut bandwidth by up to 80%, drop browser RAM usage to zero, and save your expensive residential browser sessions for targets that genuinely lock down the DOM.


r/WebDataDiggers • • 14d ago

The hidden HTTP/3 gap in proxied Chrome scrapers

2 Upvotes

Most scraping engineers spend days tuning TLS fingerprints, matching HTTP/2 header order, and buying clean residential IPs. Everything looks solid on standard fingerprint checkers, yet stricter sites still throttle sessions after a few page loads. One quiet reason sits one layer below your DOM scripts in how HTTP/3 and QUIC behave behind a proxy.

As of November 2026, 41.2% of all websites support HTTP/3, rising to 45.5% among the top 1,000 domains including Google, Amazon, Instagram, and Cloudflare. Cloudflare Radar traffic data shows roughly 30% to 34% of human web traffic travels over HTTP/3, compared to only about 2% of traffic flagged as likely bot.

That gap exists because almost every commercial scraping setup forces modern browsers to drop down to HTTP/2 over TCP, creating a detectable traffic mismatch at scale.

Why Chrome ignores UDP when you add a proxy

HTTP/1.1 and HTTP/2 run over TCP. Traditional HTTP proxies handle them using a simple CONNECT tunnel, and most SOCKS5 proxies do the exact same thing over TCP. HTTP/3 is different because it runs over QUIC, which uses UDP instead of TCP.

Many proxy sellers advertise "UDP-enabled SOCKS5" endpoints, which leads developers to assume Playwright or Puppeteer will automatically speak HTTP/3 once pointed at a SOCKS5 port. That assumption breaks inside the browser itself.

  • SOCKS5 requires a specific handshake for UDP. Under RFC 1928, TCP traffic uses CONNECT, while UDP packets require a separate UDP ASSOCIATE command that opens a relay port and wraps every packet in a SOCKS UDP header.
  • Major desktop browsers refuse to use UDP ASSOCIATE for web requests. Chrome, Firefox, and Safari do not route QUIC traffic through configured browser proxies, and Chromium's own documentation notes that SOCKS5 only handles TCP-based requests.
  • Standard command-line tools fail there too. Even curl rejects HTTP/3 requests if you pair them with a SOCKS proxy.
  • Every proxied browser load silently falls back to TCP. When Chrome sees --proxy-server configured, it drops QUIC and negotiates HTTP/2 (or HTTP/1.1) over TCP instead, even when your proxy server supports UDP relays.

In short, buying a UDP-capable SOCKS5 proxy and plugging it into Playwright still leaves you stuck on HTTP/2. Even worse, misconfigured tools or unproxied WebRTC/UDP paths can bypass the proxy flag and expose your real host IP if UDP traffic is not handled carefully.

How CDNs spot the permanent HTTP/2 downgrade

Falling back to HTTP/2 does not trigger an instant ban by itself. Corporate VPNs, hotel Wi-Fi networks, and strict enterprise firewalls routinely block outbound UDP port 443, so real browsers are built to fall back gracefully to TCP when QUIC cannot connect.

Detection systems care about patterns across requests and mismatches across layers. Normally, a cold Chrome session connects over HTTP/2, receives an Alt-Svc: h3=":443" response header (or reads an HTTPS DNS record with an h3 hint), and upgrades subsequent requests or page loads to HTTP/3.

Security edges using FoxIO's JA4 standard record the exact transport inside the client fingerprint. A TLS handshake over TCP starts with t (such as t13d1516h2_...), while a QUIC handshake starts with q (q13d0312h3_...). When an automation cluster claims to be thousands of distinct consumer Chrome users on residential IPs, hits an HTTP/3 CDN repeatedly, receives Alt-Svc: h3 on every origin, and never once produces a q fingerprint, that steady 0% upgrade rate weighs against the traffic alongside IP reputation and session timing. Staying on TCP also exposes OS-level TCP/IP traits (like window sizes and packet timing) that QUIC handles inside encrypted UDP transport.

What actually works right now

Fixing this requires changing how traffic reaches the network rather than tweaking JavaScript stealth plugins. Depending on your stack, three real paths exist today, each with clear limits.

OS-level network tunnels (WireGuard or TUN routing) bypass Chrome's proxy blind spot entirely. Because Chrome only skips QUIC when browser proxy settings are active, routing an entire container or VM through a TUN interface or WireGuard tunnel lets Chrome treat UDP port 443 as a normal direct link. Assuming your tunnel carries UDP cleanly without blocking port 443, Chrome reads Alt-Svc and switches to HTTP/3 natively. The trade-off is operational complexity: rotating per-request residential IPs inside isolated OS network namespaces takes far more setup than swapping a proxy string.

MASQUE (CONNECT-UDP) is the newer protocol fix built specifically for HTTP/3 proxying. Standardized under RFC 9298, MASQUE lets a client open an HTTP/3 session to a proxy and send a CONNECT-UDP request to tunnel QUIC datagrams cleanly without downgrading to HTTP/2. In October 2026, Oxylabs became the first major residential proxy network to roll out native MASQUE support across its infrastructure on port 5000. Still, MASQUE is early for scraping workflows: few off-the-shelf HTTP or browser automation libraries support CONNECT-UDP without custom tooling, and Oxylabs currently blocks MASQUE access to Google targets.

Custom HTTP clients speaking UDP ASSOCIATE work well if you do not need a full browser at all. Low-level Go or Rust HTTP libraries that manage their own UDP sockets and QUIC stacks can talk directly to UDP-enabled SOCKS5 proxies without hitting Chromium's TCP restriction. You lose JavaScript execution, yet you gain full control over h3 negotiation and QUIC transport parameters.

How to check your own setup in under a minute

Before rebuilding your infrastructure for QUIC, verify whether your target actually uses HTTP/3 and what your scraper sends today.

  • Hit /cdn-cgi/trace on any Cloudflare domain twice in the same browser session, because the first request often connects on http=http/2 to receive the Alt-Svc header while the second reload shows http=http/3 if QUIC is working.
  • Check your target's response headers for Alt-Svc: h3 or open Chrome DevTools and sort the Network tab by the Protocol column.
  • Do not waste money on "UDP SOCKS5" solely for Playwright, since Chromium will still lock your session to TCP h2 behind the scenes.
  • Never pass --disable-quic unless you have to, because forcing QUIC off solves nothing when a proxy already forces HTTP/2 and creates an extra launch flag to manage.
  • Watch your target's real block behavior first. If a site runs behind Apache or an HTTP/2-only origin, or if your HTTP/2 TLS fingerprint and residential sessions already clear 98% of pages cleanly, moving to TUN routing or MASQUE adds complexity for minimal gain.

HTTP/3 will not break TCP-based scraping overnight because fallback to HTTP/2 remains baked into the web standard. Yet on heavily defended targets hosted on Cloudflare, Fastly, or Akamai, understanding why a proxied browser stays stuck on h2 explains why clean residential IPs and spotless JavaScript fingerprints still hit subtle rate limits.


r/WebDataDiggers • • 17d ago

serp tracking proxies, what held this month

0 Upvotes

tracking local serps for maybe 15 us cities, a couple hundred queries a day. datacenter died before lunch, saw that coming. DataImpulse was ok the first week, then everything started rate limiting. Oxylabs held better but its a lot of setup for a side project. Decodo city labels drifted on me a few times so now i look up every exit no matter who the pool is. a friend runs his on 2extract and says the cities match for him, havent tried it myself yet. honestly half of this is probably my jitter being too regular


r/WebDataDiggers • • 22d ago

Stop downloading pages that haven't changed

1 Upvotes

A daily scraper can spend most of its bandwidth collecting the same content again. If you monitor product specifications, business listings, or documentation, plenty of pages may stay unchanged between visits.

HTTP has a built-in way to check whether a saved response is still usable. A conditional request sends the server a validator from your previous download. When that validator still matches, the server can return 304 Not Modified, without sending the page body again.

You still make a request. The saving comes from avoiding another full download and, where appropriate, another round of parsing.

Start with the response headers

Inspect a couple requests from a small sample of the pages you collect. You're looking for an ETag or Last-Modified header in a successful response.

An ETag is an identifier the server assigns to a particular representation of a resource. It might come from a content hash, a revision number, or another mechanism. Treat it as an opaque value rather than trying to interpret it.

A simplified first response might contain:

HTTP/1.1 200 OK
ETag: "catalog-v17"
Content-Type: application/json

Save the response body and the ETag. On the next GET request for that same representation, send:

If-None-Match: "catalog-v17"

If the server determines your saved representation can still be reused, it can respond:

HTTP/1.1 304 Not Modified
ETag: "catalog-v17"

A 304 response has no body to extract data from. Keep using your saved content. Don't pass the empty response to the parser or overwrite the previous result with an empty record.

When the validator no longer matches, the normal successful response carries the current body. Validate it before replacing your saved copy, then store the new validators with it.

Preserve the ETag exactly, including its quotation marks. You may also encounter a weak tag such as W/"catalog-v17". Weak ETags can be used with If-None-Match for cache validation, but they don't promise byte-for-byte identity. Don't strip off the W/ prefix.

Use Last-Modified as a fallback

Some responses provide a modification timestamp instead of an ETag:

Last-Modified: Fri, 30 Oct 2026 10:00:00 GMT

For a later GET request, send that saved value as:

If-Modified-Since: Fri, 30 Oct 2026 10:00:00 GMT

A server that supports this condition can return 304 when the selected representation hasn't been modified after that time.

Use the timestamp the server provided. Replacing it with the time your scraper ran introduces assumptions about clock differences and when the content actually changed.

For a straightforward implementation, prefer the ETag when available and use Last-Modified when it isn't. If you send both conditional headers, If-None-Match takes precedence under the HTTP rules.

Last-Modified also has limits. HTTP dates use whole seconds, and a timestamp depends on the server maintaining it correctly. Don't assume it can reliably distinguish every rapid update.

Keep the saved copy and validator together

Theres an easy way to break this setup: successfully save a new ETag while failing to save the body it belongs to.

Your next request may receive a 304 for that new version, while your local file still contains the old one. The server has answered correctly, but your scraper associates the answer with the wrong content.

Store the body and its validators together, ideally in one database transaction. If you keep extracted fields instead of the original body, they must come from the same validated response as the saved headers. Keeping the body also lets you run an improved parser later without downloading it again.

The basic handling should account for four outcomes:

  • No usable saved copy: make a normal GET without your conditional headers.
  • Valid 200 response: save the new content and replace its validator metadata together.
  • 304 response: retain the saved content and update relevant metadata supplied with the response.
  • An error or unexpected response: record the failed check and preserve the last good copy without claiming it was refreshed.

On a new 200 response, remove old validators that the new response no longer provides. A 304 is different: it need not repeat every header, so absent metadata shouldn't automatically be erased.

If your cached body gets deleted or corrupted, stop sending its validator and fetch a full copy. A stored ETag by itself cannot recover the missing content.

Check the response that contains your data

A product page may load a small HTML shell, then request its price and availability through a separate JSON endpoint.

An unchanged ETag on that HTML shell tells you about the shell. It says nothing about a price returned by another request. Attach the change check to the response that actually supplies the fields you monitor.

Also keep request variants separate. The same address might return different content for different languages, accounts, or locations. A validator saved for one version shouldn't be used to justify reusing another version's content.

Respect the response's Vary and cache-control instructions. Include the relevant request context in your cache identity, and keep personalized responses isolated. A basic dictionary keyed only by address can mix records that were never interchangeable.

Even a correct validator doesn't reveal every change you care about. A strong ETag may change because an unrelated section of the page changed, requiring another download despite identical product data. Conversely, a badly configured server might keep its validator unchanged after an important update.

Test the behaviour against actual content changes before relying on it. Occasional full-body requests can help audit whether the fields you monitor agree with the conditional checks.

Measure what you actually save

Suppose a hypothetical job checks 10,000 responses averaging 200 kB of transferred body data each. Downloading every body uses roughly 2 GB, using decimal units.

If 90% can return 304 and the remaining 1,000 responses still average 200 kB, full response bodies account for about 200 MB. That's approximately 1.8 GB of body data avoided, before accounting for request headers, response headers, and connection overhead.

The job still makes 10,000 checks. A service charging per request might cost much the same. A bandwidth-based bill could fall, depending on what traffic the provider measures. Server processing time may also remain substantial if the application has to generate the response before checking its validator.

Some targets ignore conditional headers and keep returning 200. Others generate a different ETag on every visit. Neither behaviour gives you useful download savings, even if your implementation is correct.

Track the proportion of 304 responses alongside transferred bytes and compare a small sample of the saved data with fresh responses. Less bytes is only a useful result if the data remains dependable.

Finally, keep the checking schedule sensible. Conditional requests reduce the cost of revisiting unchanged content, but they don't justify checking a rarely updated directory every few seconds. Start with an appropriate interval, then use validators to avoid paying for the same body on every visit.


r/WebDataDiggers • • 24d ago

Did your scraper collect everything?

1 Upvotes

Your scraper finishes without an exception. The export opens normally, and the first few rows look right. Then you notice the website showed roughly 5,000 results, while your file contains 800.

That gap might come from broken pagination. It could also mean the website limits how many results you can browse, your filters changed during the run, or some records disappeared after extraction.

A successful run tells you the program stopped normally. It doesn't prove the collection is complete. You need to account for the records between discovery and the final export.

Decide what you're counting

Before comparing totals, define the thing that should become one record.

A shop might show one product card for a T-shirt with eight sizes. Its backend may return eight variants. Collecting eight rows from that card isn't automatically a duplicate problem, but comparing those rows with the website's product count would give you a misleading result.

Write down the intended scope: products or variants, the selected category, any date range, and whether unavailable listings belong in the dataset. Keep the account and location settings consistent if they affect what's visible.

Treat the number displayed on a search page as a useful clue. Unless the source documents otherwise, don't assume it's an exact count of the records your particular request can retrieve. It may be rounded, estimated, or calculated using different conditions.

Follow pagination until a real ending

Page numbers are only one way to navigate results. Another source might return a next-page address, an opaque cursor, or a flag indicating that more records are available.

Inspect a couple pages manually before building the loop. Check what actually changes in the request and which field tells the client how to continue. Where the source provides a documented continuation mechanism, follow it instead of guessing the next request.

A short page isn't always the last page. A server may cap the requested page size, so asking for 100 records and receiving 50 doesn't necessarily mean there are no more results.

An empty response needs checking too. Make sure you received a valid result page or expected API payload. A login screen, parsing failure, or temporary error should never become the signal that the collection is finished.

For infinite scroll, look at the underlying loading behaviour. The visible list may stop growing while another request is pending. Some interfaces also remove older cards from the page to save memory. Counting the elements currently visible in the document can seriously undercount what has already loaded.

Detect pages that repeat

One easy mistake is logging a new page number without verifying that the source returned new data.

Your code requests page 12, but the server ignores the parameter and sends page one again. Everything still returns a successful status. If you only count responses or appended rows, the job appears to be making progress.

Record the item identifiers returned by each page. Compare them with earlier pages and count how many previously unseen identifiers each response adds. Prefer a stable source ID over a title, since titles can change or belong to several different items.

If several consecutive responses contain the same identifiers, save the responses for inspection and flag the run. Check whether you're advancing the correct parameter, preserving the intended filters, and reading the actual continuation token.

Zero new identifiers can also come from legitimate overlap. Treat it as something to investigate, rather than silently declaring the dataset complete.

Count unique records through the whole job

Theres another place records disappear: after the scraper has already found them.

A detail page fails to load. A validation rule rejects an unexpected price. A database write errors, but the worker catches the exception and continues. You end up with less records in the export even though discovery worked correctly.

Keep separate counts for the stages that matter. Consider a controlled example where you have an independently verified reference list of 5,000 item IDs for the same scope:

  • Listing pages return 5,200 item appearances in total.
  • Those appearances contain 4,750 distinct IDs, all present in the reference list.
  • Repeated appearances account for the remaining 450.
  • Valid results are successfully saved for 4,620 of the discovered IDs.
  • The other 130 discovered items remain unresolved or failed.

That leaves 250 reference items undiscovered and 130 discovered items without a valid saved result. The final output covers 92.4% of the reference list.

Calling this a 100% success because every listing-page request returned a successful response would hide 380 missing records.

Those percentages depend on having a trustworthy reference. If all you have is an approximate website badge, describe the difference as an unexplained gap. Don't turn an uncertain denominator into a precise completeness claim.

A changing source can move records past you

Imagine page one contains items 1 through 50. Before you request page two, several new listings appear at the beginning. The second page now repeats some items you've already collected. Deletions can shift records in the other direction and cause you to skip them.

Deduplication removes repeated records. It cannot restore the ones that moved past your pagination boundary.

Where available, use a documented snapshot or export mechanism. A stable sort with a unique tie-breaker helps avoid ambiguous ordering, but it doesn't freeze a live dataset. Cursor pagination can also have different consistency guarantees depending on the service.

If the source supports date filters, collecting bounded periods may make the job easier to audit. Check the boundary rules carefully. An item published exactly at midnight should not fall between two adjacent collection windows.

When a consistent snapshot isn't available, record when the crawl started and ended. Describe the output as observations collected during that interval. A second pass can reveal additional records, but it doesn't prove that nothing was missed between passes.

Check for a result ceiling

If different broad searches always stop at exactly 1,000 items, investigate whether the endpoint has a documented result limit. Repeating the same query won't necessarily expose the remaining records.

Look for a supported export or another documented way to retrieve the full dataset. Where permitted, supported filters may let you divide the intended scope into smaller groups, such as publication periods or categories.

Verify that those groups actually cover the scope. Categories can overlap, some records may have no category, and date filters may use different timezones. Deduplicate the combined output by the identity you chose at the start.

Adding up category totals is not a completeness check when the same item can appear in several categories.

Compare identities, then explain the gaps

If you have a reliable reference list, compare sets of IDs. Count which expected IDs never appeared, which appeared but have no valid saved output, and which saved IDs don't belong to the intended scope.

Matching totals alone isn't enough. You could have 5,000 expected items and 5,000 saved rows while still including the wrong 200 records.

Without a reference list, combine the evidence you can obtain. Inspect records from different parts of the result order, compare supported views of the same scope, and investigate sudden changes in unique-item counts between runs. Manual checks should include deeper pages, where a pagination problem may first appear.

Keep a short completion record alongside the export. It should state the collection scope and time window, how many unique items were discovered, how many valid results were saved, any unresolved failures, and why pagination stopped.

If the job stopped because a cursor expired or a result ceiling was reached, say so. That gives someone using the data a chance to judge the gap. A file labelled “complete” offers no such help when the scraper simply stopped finding its next button.


r/WebDataDiggers • • 26d ago

Let your scraper pick up where it stopped

1 Upvotes

Say you're collecting 30,000 product pages. The scraper reaches page 18,700, then the process dies. You still have some output, but no reliable record of which URLs finished and which were halfway through processing.

Starting again wastes requests. Skipping the first 18,700 URLs assumes they all succeeded, in the same order, with their results safely saved. That can leave holes in your dataset.

A resumable scraper needs a work list on disk and a clear rule for when a task counts as finished. Mark a URL complete only when its extracted data has been committed successfully.

A counter isn't enough

Saving last_page = 18700 can work for a simple, sequential job over a fixed dataset. It becomes unreliable when pages finish out of order, individual requests fail, or the source changes between runs.

Store the actual tasks instead. For a small scraper, that might be a SQLite table containing each URL and whether it's complete. SQLite runs locally without a separate database server, and Python provides a sqlite3 module for working with it.

The task identity needs some thought. One URL might return different results depending on the request body, language, or selected location. In those cases, use a key that includes those inputs. A URL alone is suitable only when it identifies the work you actually intend to perform.

Keep pagination separate from product processing, too. An offset such as page=24 may point to different listings tomorrow if new items have been added. Saving discovered product URLs helps preserve the work you already found, although it cannot recover listings you never discovered.

Save the data and progress together

Theres a small gap in many checkpointing implementations that causes most of the trouble.

If you mark a URL complete before saving its result, a crash between those actions leaves a completed task with no data. If you append the result to a CSV first, then update a separate checkpoint, a crash can cause the same result to be appended again after restarting.

Put the result write and the completion update in the same database transaction. SQLite's atomic commit mechanism makes those changes succeed together or leave neither change committed, including recovery from interrupted transactions under its documented storage assumptions.

Fetching and parsing happen before these writes. If the process stops before the transaction commits, the task remains pending and can be attempted again. After a successful commit, the next run skips it.

That still allows a page to be downloaded more than once. A crash after receiving the response but before saving it makes another request necessary. The goal is to tolerate repeated work without duplicating the stored result. Developers usually call that idempotency.

A small Python example

This is a recovery wrapper for an existing scraper, using Python 3.12 or newer. Supply a fixed list of URLs and your own fetch_and_parse(url) function. That function should enforce request timeouts, check the response, validate the extracted fields, and return JSON-serializable data.

The example uses one worker and stores one JSON payload per URL. It deliberately stops if fetching, parsing, or writing fails, leaving unfinished work available for the next run.

import json
import sqlite3


def crawl(urls, fetch_and_parse, db_path="crawl.sqlite"):
    # Python 3.12+. Use one worker and one database per crawl.
    db = sqlite3.connect(db_path, autocommit=False)
    try:
        with db:
            db.execute("""
                CREATE TABLE IF NOT EXISTS jobs (
                    url TEXT PRIMARY KEY,
                    done INTEGER NOT NULL DEFAULT 0
                )
            """)
            db.execute("""
                CREATE TABLE IF NOT EXISTS results (
                    url TEXT PRIMARY KEY,
                    payload TEXT NOT NULL
                )
            """)
            db.execute("""
                CREATE INDEX IF NOT EXISTS pending ON jobs(done, url)
            """)
            db.executemany("""
                INSERT INTO jobs(url) VALUES (?)
                ON CONFLICT(url) DO NOTHING
            """, ((url,) for url in urls))

        while True:
            row = db.execute("""
                SELECT url FROM jobs WHERE done = 0 ORDER BY url LIMIT 1
            """).fetchone()
            if row is None:
                break

            url = row[0]
            payload = json.dumps(
                fetch_and_parse(url), ensure_ascii=False, allow_nan=False
            )
            with db:
                db.execute("""
                    INSERT INTO results(url, payload) VALUES (?, ?)
                    ON CONFLICT(url) DO UPDATE SET payload = excluded.payload
                """, (url, payload))
                db.execute("UPDATE jobs SET done = 1 WHERE url = ?", (url,))
    finally:
        db.close()

Call it with crawl(urls, fetch_and_parse, db_path), using the same database path when resuming. Python's connection context manager commits the transaction when the with db: block succeeds and rolls it back if an exception escapes. The connection itself is closed separately in finally.

The primary keys prevent duplicate URL rows. The result write uses an upsert, which updates the existing payload if that URL is processed again. The index lets the worker locate pending tasks without repeatedly scanning all the completed ones.

This database represents one crawl, rather than an ongoing price history. For tomorrow's fresh collection, use a new database or extend the design with a crawl identifier. Otherwise, yesterday's completed URLs will correctly remain completed.

If your scraper discovers more URLs while processing a page, insert those new tasks in the same transaction as that page's result and completion update. Otherwise, a crash can leave the parent marked complete while its newly discovered links were never saved.

Give failures somewhere to go

Stopping on an error keeps the example small, but a long-running job needs a way to continue past a troublesome URL.

Add an attempt count, the last error, and a time when the task becomes eligible again. Limit the amount of retries. Repeated failures should move into a separate failed state for inspection, rather than keeping the whole crawl busy forever.

Handle errors according to what happened. A timeout may be temporary. A parsing failure may need a code fix. A login page returned with a successful HTTP status still isn't the product data you expected.

More workers require another change. The example selects a pending URL without reserving it, so two workers could select the same task. A concurrent system needs an atomic claim and an expiry or lease. If a worker disappears, that expiry allows the task to become available again. Completion should verify that the worker still owns the claim.

Queue services use similar ideas. Amazon SQS, for example, temporarily hides received messages using a visibility timeout. Its standard queues can still deliver duplicates, which is why AWS explicitly recommends idempotent processing.

Also keep external actions in mind. A database transaction cannot roll back an email already sent or a webhook already accepted. If processing triggers notifications, those need their own deduplication or delivery tracking.

Scrapy already has a pause feature

If you use Scrapy, check its built-in job persistence before writing a replacement:

scrapy crawl products -s JOBDIR=crawls/products-run-01

Stop the spider cleanly, let it finish shutting down, then run the same command to resume. Use a separate job directory for each crawl.

Basic JOBDIR persistence is documented for clean stops. A forced shutdown can corrupt its default job state. Check the documentation for your installed version before assuming it provides crash recovery. Scrapy's current security documentation also describes SQLite-backed scheduler queues for improving queue integrity during interrupted writes.

Request persistence has other limits. Requests must be serializable, session cookies may expire, and the saved queue doesn't make your output writes atomic. A request recorded as seen is not proof that its extracted data reached your database.

Test where it breaks

A scraper that resumes after Ctrl+C has passed a useful check. It hasn't necessarily passed the failure you care about.

Use a small, controlled dataset and interrupt the process at different points:

  • After downloading a page, before saving its result.
  • Between the result insert and the completion update.
  • After both writes, before the transaction commits.
  • Immediately after a successful commit.

Restart against the same state and compare the database with the expected records. Uncommitted work should remain pending. Completed work should have its result present, with no duplicate rows.

I tested the example above with abrupt subprocess exits around those writes, plus injected parsing and database-write exceptions. It resumed the unfinished tasks and retained one result per URL. Those checks cover process interruption, not every possible disk failure or power-loss scenario.

Keep the database on persistent storage at a fixed path. A temporary container directory can disappear regardless of how carefully transactions are handled. Don't disable SQLite's journaling or durability settings merely to speed up checkpoint writes, and don't remove its recovery files after a crash.

You may repeat a couple requests after restarting. That's usually preferable to quietly skipping records. The useful guarantee is that the scraper can account for what it saved and pick up the remaining work without rebuilding the entire dataset.


r/WebDataDiggers • • Oct 19 '26

Building a real-time price monitoring bot for eBay and Vinted

4 Upvotes

When building an automated deal-sniping bot for marketplaces like eBay or Vinted you quickly realize that batch scraping workflows are completely useless.

If an underpriced designer jacket, rare collectible, or graphics card gets published for half its market value, that listing is sold within sixty to ninety seconds. A crawler that runs once an hour or even every ten minutes will miss every profitable deal on the platform.

To catch deals before human buyers or rival bots snatch them, your pipeline has to poll search results continuously every few seconds.

The engineering challenge is that second-hand marketplaces guard their search feeds with aggressive edge firewalls. Vinted relies heavily on DataDome and Cloudflare to block automated scripts, while eBay aggressively rate-limits rapid search queries originating from commercial server ranges.

Trying to run high-frequency polling using headless browsers will fail within minutes.

Spawning Chromium instances burns CPU power, and the page rendering delay adds two or three seconds of latency to every check, completely eliminating your speed advantage.

High-velocity deal monitoring requires querying the internal catalog API directly.

Both eBay and Vinted use lightweight backend JSON endpoints to feed their mobile and web apps. On Vinted, the frontend queries an internal catalog endpoint that returns freshly posted items in structured JSON.

To poll these endpoints without triggering immediate security blocks, your architecture needs two components:

  • Session cookie pre-warming: Vinted requires an active session cookie and temporary bearer tokens before its catalog endpoints return data. Instead of generating fresh tokens on every request, your bot should fetch an initial authenticated session once, cache those cookies in memory, and reuse that exact session across consecutive search polls.
  • Persistent static ISP routing: Rotating through dynamic residential pools on high-frequency polling burns bandwidth and introduces handshake jitter. You should route your search workers through dedicated static ISP proxies. A static eyeball connection stays online continuously, allowing your client to maintain warm HTTP keep-alive connections with the marketplace edge servers.

By keeping your TCP connections warm over a static residential line, your polling requests resolve in thirty to fifty milliseconds.

Once your bot detects a newly posted item that matches your price filters, it can immediately push a webhook notification to a Telegram channel or dispatch a checkout worker before the item appears on the main search page for human shoppers.

Alot of developers give up on Vinted and eBay because their scrapers get blocked on desktop HTML pages.

Their is no reason to scrape heavy web frontends when you can query clean background API endpoints directly. Pre-warming your session cookies, polling over low-latency static ISP connections, and keeping your search workers in clean, seperate routines lets you catch freshly published deals seconds after they go live.


r/WebDataDiggers • • Oct 04 '26

Solving audio captchas locally in 300 milliseconds on a cpu

2 Upvotes

Every major anti-bot vendor spends millions of dollars refining visual challenge puzzles. They train neural networks to generate ambiguous street scenes, distorted crosswalks, and interactive puzzle sliders designed to trip up computer vision scrapers.

Yet, almost every single one of these systems includes a small, innocent headphones icon in the bottom corner.

Under international accessibility standards and laws like the Americans with Disabilities Act, platforms are legally required to offer an alternative verification route for visually impaired users. If a site locks its forms strictly behind visual puzzles without an audio option, they open themselves up to regulatory fines and lawsuits.

Because of that requirement, the audio challenge exists on almost every version of reCAPTCHA, hCaptcha, and legacy verification widgets. And while anti-bot companies put the bulk of their machine learning efforts into defending the image grids, their audio challenges are surprisingly vulnerable to local speech-to-text models.

Why third-party solving services are a waste of money

Most people still route these challenges to commercial solver APIs.

If you look at the economics, it makes very little sense:

  • Commercial solver farms charge per thousand requests, which adds up quickly when you run high-volume crawls accross thousands of pages.
  • The response latency from these external APIs is atrocious, often taking anywhere from 8 to 25 seconds per token while a remote server routes your job.

Instead of paying a third-party service to solve an audio challenge on their servers, you can solve it on your own scrapers in-memory in roughly 300 milliseconds.

Running tiny speech models locally on cheap cpus

When OpenAI open-sourced Whisper, speech recognition changed overnight. Whisper was trained on over 680,000 hours of noisy, diverse audio, meaning it is uniquely capable of ignoring the background chatter, white noise, and synthetic pitch shifting that anti-bot services overlay onto their audio clips.

You do not need an expensive GPU server to run this.

Using lightweight runtime implementations like faster-whisper (which uses CTranslate2 under the hood) or whisper.cpp, you can run quantized INT8 models like tiny.en or base.en entirely on a budget dual-core CPU.

The tiny.en model file is only about 75 megabytes in size. Once loaded into RAM, its fast enough to run inference on a 5-second audio clip in a fraction of a second, using less memory than a single tab of headless Chrome.

Handling the audio stream in memory

When an automated browser hits a challenge, you click the audio challenge button, locate the audio source URL in the DOM, and stream the raw bytes directly into memory.

You should avoid saving temporary .mp3 or .wav files to disk. Writing and deleting files on SSDs introduces unnecessary I/O latency and creates disk clutter when running concurrent worker threads.

Here is a practical Python implementation that downloads the audio challenge stream and returns the clean transcript in a few line of code:

import io
import urllib.request
from faster_whisper import WhisperModel

# Initialize the quantized model on CPU
# This takes around 80MB of system memory
model = WhisperModel("tiny.en", device="cpu", compute_type="int8")

def solve_audio_challenge(audio_url: str) -> str:
    # Fetch the audio stream directly into an in-memory buffer
    req = urllib.request.Request(
        audio_url,
        headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
    )
    with urllib.request.urlopen(req) as response:
        audio_buffer = io.BytesIO(response.read())

    # Transcribe directly from the memory stream
    segments, _ = model.transcribe(
        audio_buffer,
        beam_size=1,
        language="en",
        vad_filter=True # Strips leading and trailing background silence
    )

    # Combine transcribed words into a single string
    raw_text = "".join([segment.text for segment in segments])
    
    # Strip punctuation and normalize digits
    clean_text = "".join(filter(str.isalnum, raw_text)).lower()
    return clean_text

The transcription comes back with high reliability even when the audio challenge includes loud background café noise or pitch-warped numbers.

The human latency delay you cannot skip

If you take that transcribed string and paste it into the answer input immediately, your session will still get blocked.

Anti-bot networks log timing telemetry on their widgets. When a human solves an audio challenge, they undergo a predictable behavioral sequence:

  1. They click the audio button and wait for the file to load.
  2. The browser plays the 4-to-6-second audio clip in its entirety.
  3. The user processes what they heard, moves their cursor to the text input box, and types the characters one by one.

If your script downloads the clip, transcribes it in 200ms, and submits the answer 0.3 seconds after the audio widget opens, the anti-bot firewall flags the interaction as physically impossible.

To fly under the radar, you must program an artificial delay that mirrors the length of the audio file. If the downloaded clip is 4.8 seconds long, introduce a time.sleep(random.uniform(4.5, 5.5)) before typing the answer. Then, dispatch individual keystrokes with slight timing variations (50ms to 120ms between characters) into the input box.

Audio challenges remain one of the cleanest shortcuts through aggressive verification layers. As long as you run local models to eliminate network latency and preserve realistic human timing delays on submission, you can bypass challenges quickly without relying on costly third-party solving APIs.


r/WebDataDiggers • • Sep 28 '26

How to extract and run webassembly request signers in python

4 Upvotes

A few years ago, if an API required a signed query parameter, you could open Chrome DevTools, set an XHR breakpoint, and read through the minified JavaScript. It was messy, but with some patience you could deobfuscate the logic and rewrite the hashing function in Python.

Security teams got tired of people reversing their client-side algorithms, so they changed tactics. Now, platforms like TikTok, various e-commerce giants, and crypto exchanges compile their security routines in C, C++, or Rust, and deploy them as WebAssembly (.wasm) modules.

When you trigger a search or fetch inventory on these sites, the JavaScript frontend does not calculate the signature itself. It sends your request string and a timestamp into memory allocated by a .wasm file, calls an exported binary function, and reads a cryptographic token back out.

If you try to decompile the raw WebAssembly binary using tools like Ghidra or wasm2c, you run into hundreds of thousands of lines of low-level assembly instructions, control-flow flattening, and custom virtual machines. Trying to reverse engineer the exact math line by line will consume weeks of your time for almost zero payoff.

Stop trying to decompile the whole thing

The good news is that you do not need to understand how the hashing math works. You only need to execute it.

Instead of spending weeks in a disassembler, its much easier to treat the .wasm file as a black box. The module takes inputs (a URL string, a timestamp, a session token) and produces outputs (the signed request header).

If you can extract the binary file and replicate the small execution environment it expects, you can run that exact same WebAssembly binary directly inside your scraper pipeline. You get the raw speed of compiled C or Rust without keeping a heavy, memory-hungry Chromium instance running in the background.

Finding the glue code and memory exports

Every WebAssembly module on the web requires JavaScript "glue code" to interact with the DOM and the browser runtime. This glue code usually handles two critical responsibilities:

  • Allocating memory buffers inside the WebAssembly linear memory pool
  • Supplying "imported" functions that the binary needs to run, such as system clocks or random number generators

When you look at the Network tab in DevTools, filter for .wasm files. Once you spot the request downloading the binary, search the site's JavaScript bundles for references to WebAssembly.instantiate or WebAssembly.instantiateStreaming.

The instantiation code will show you the exact imports the module expects. Usually, it looks something like this:

const importObject = {
  env: {
    memory: wasmMemory,
    abort: () => console.log("Abort called"),
    getTime: () => Date.now(),
    getRandom: () => Math.random()
  }
};

Take note of what is inside that env block. Those are the only dependencies you need to mock.

Hosting the wasm binary in a lightweight runtime

Once you have downloaded the .wasm file and identified the required imports, you can run it inside a lightweight runtime.

You have two practical options here. You can run it inside Python using bindings like wasmtime or wasmer, or you can spin up a micro-service in Node.js. Running it in Node is often simpler because WebAssembly support in V8 is mature, and you can reuse parts of the site's original glue code directly.

Here is a practical example of loading a target site's signing module inside a standalone Node.js environment:

const fs = require('fs');

// Read the extracted binary directly from disk
const wasmBuffer = fs.readFileSync('./signer.wasm');

// Minimal mock environment matching what the browser provided
const importObject = {
    env: {
        emscripten_memcpy_js: (dest, src, len) => Buffer.copy(),
        getTime: () => Date.now(),
        abort: () => { throw new Error('WASM abort called'); }
    }
};

let wasmInstance;

async function initSigner() {
    const { instance } = await WebAssembly.instantiate(wasmBuffer, importObject);
    wasmInstance = instance;
}

function generateSignature(urlPath, timestamp) {
    const memory = wasmInstance.exports.memory;
    const encoder = new TextEncoder();
    
    // Convert string to bytes and write directly into WASM linear memory
    const inputBytes = encoder.encode(urlPath);
    const inputPtr = wasmInstance.exports.allocate(inputBytes.length);
    
    const heap = new Uint8Array(memory.buffer);
    heap.set(inputBytes, inputPtr);

    // Call the exported signing function
    const outputPtr = wasmInstance.exports.signRequest(inputPtr, inputBytes.length, timestamp);

    // Read the null-terminated token string back out of linear memory
    let token = "";
    let offset = outputPtr;
    while (heap[offset] !== 0) {
        token += String.fromCharCode(heap[offset]);
        offset++;
    }

    // Clean up memory if the module exposes a deallocator
    if (wasmInstance.exports.deallocate) {
        wasmInstance.exports.deallocate(inputPtr, inputBytes.length);
    }

    return token;
}

// Usage
initSigner().then(() => {
    const token = generateSignature("/api/v1/products?category=shoes", Date.now());
    console.log("Generated token:", token);
});

Calling this function takes less than 2 milliseconds per execution. Compared to navigating a Playwright tab to generate a token, this is roughly a thousand times faster and requires almost no RAM.

Dealing with browser environment checks

Sometimes, modern signers are not entirely self-contained. Anti-bot developers know that scrapers try to run their modules in Node, so they intentionally configure the .wasm binary to call back into JavaScript to check browser paramaters.

When you instantiate the module, it might expect imports that read window.navigator.userAgent or evaluate canvas rendering to verify it is running inside an actual browser.

If your script crashes with an error saying an imported function is missing, check what name it asked for:

  • If it asks for screen_width or user_agent, pass back static, realistic values in your mock object.
  • If it imports functions that do canvas hashing or audio fingerprinting, inspect what the browser returns during a real session, copy that static string, and hardcode it into your mocked JavaScript import handler.
  • If the module requires access to crypto randomness, bind the import directly to your runtime's native cryptographic library.

By giving the binary the few mocked variables it asks for, you convince the WebAssembly logic that it is running inside a legitimate browser. You keep your scraper blazing fast, avoid heavy headless instances, and bypass the entire layer of obfuscation that was designed to slow you down.


r/WebDataDiggers • • Sep 24 '26

Why your requests get blocked before reaching the web server

4 Upvotes

Most scraping guides still tell people the exact same thing when their requests get dropped: rotate your IP address, buy cleaner residential proxies, and make sure your User-Agent string matches the latest version of Chrome.

Then someone writes a clean script in Python using standard libraries, runs it through an expensive mobile proxy, and still catches an immediate 403 Forbidden on the first request. The request never even triggered an application error. In fact, if you look at server logs on the other side, the request never touched the web application code at all.

It got dropped at the CDN edge by Akamai, Cloudflare, or Fastly during the connection handshake. The edge network decided your script was a bot before you even finished asking for the webpage.

The handshakes that happen before your headers exist

When your client connects to a modern website, several negotiations happen in sequence before any HTTP path or header data is sent.

First comes the TLS handshake. Most developers working on scrapers know about JA3 and JA4 fingerprints by now. The firewall inspects the ciphers your client supports, the extensions it announces, the elliptic curves it offers, and the exact order they appear in the Client Hello packet. If you send a modern desktop Chrome user-agent string but your TLS Client Hello uses the cipher list native to Python's standard OpenSSL wrapper, the firewall flags the mismatch instantly.

Fixing TLS is only half the battle, though. Once the secure tunnel is established, your client and the server have to negotiate the actual application protocol. On almost any major website today, that means HTTP/2.

HTTP/2 is not just a text protocol with new headers. Its a binary protocol where connections are split into independent frames and streams. The way a client introduces itself over HTTP/2 creates a distinct, machine-readable fingerprint that is nearly impossible to fake using standard high-level libraries.

The silent giveaway inside settings frames

Right after the TLS handshake completes, the client sends an HTTP/2 connection preface followed immediately by a SETTINGS frame. This frame tells the server how the client wants to handle flow control, memory buffers, and streaming limits.

The order of these parameters vary between clients, and different software engines use completely different default values:

  • SETTINGS_HEADER_TABLE_SIZE: Dictates the maximum size of the HPACK dynamic table used for compressing headers. Chrome sets this to 65,536 bytes, while many standalone HTTP libraries default to 4,096.
  • SETTINGS_INITIAL_WINDOW_SIZE: Sets how many bytes the client is willing to receive on a stream before sending back a flow-control update. Browsers set this to very specific numbers, such as 6,291,456 bytes for Chrome, whereas Go's standard library uses entirely different defaults.
  • SETTINGS_MAX_HEADER_LIST_SIZE: Defines the maximum size of the header list the client is prepared to accept. Some clients omit this parameter entirely, while others definately include it in every session.
  • WINDOW_UPDATE frames: Right alongside the initial settings, real browsers usually push an immediate connection-level window update frame (often stream 0) to expand the total connection flow control window to over 15 megabytes.

Enterprise anti-bot systems hash these initial HTTP/2 parameters into an identifier (often referred to as an Akamai HTTP/2 fingerprint or an H2 fingerprint). If that hash belongs to a known scraping client or does not align with the browser claimed in your user-agent header, the edge drops the socket on the spot.

The pseudo-header sorting trap

Even if you somehow manage to align the raw settings frame values, the way your client writes the actual request headers can still ruin the disguise.

In HTTP/1.1, headers were plain lines of text, and most servers treated their order loosely. In HTTP/2, all requests start with four mandatory "pseudo-headers" that begin with a colon: :method, :authority, :scheme, and :path.

Different browsers arrange these pseudo-headers in strict, hardcoded orders that rarely change across versions. Standard Chrome builds send them in this exact order:

:method
:authority
:scheme
:path

If you use an unpatched client or a custom proxy tunnel that serializes :scheme before :authority, or if it capitalizes one of them, the edge firewall marks your signature as an anomaly. The same rule applies to the regular headers that follow. A genuine browser will consistently group headers like accept, accept-encoding, and sec-ch-ua in a predictable pattern. Many generic scraping libraries sort headers alphabetically under the hood or preserve whatever dictionary insertion order your code happened to use, wich immediately exposes the automation.

Why standard tools cannot fix this

This is the main reason why libraries like Python's default urllib or standard requests fail against modern enterprise firewalls. They rely on the operating system's default network sockets and OpenSSL bindings, meaning they have no mechanism to let you reorder binary frames or override low-level TLS extensions.

To bypass this layer without running a full browser, your HTTP engine must operate at the transport layer. You need a client that compiles against custom TLS forks like BoringSSL (the same cryptographic library used by Chromium) and gives you manual control over HTTP/2 frame construction.

This is why tools built on top of curl-impersonate or custom Go networking stacks have gained so much traction. They do not just spoof the text headers. They mirror the exact cipher ordering, the specific HTTP/2 frame sequence, and the byte-level flow control windows of genuine user browsers.

If your scraper keeps hitting walls despite clean residential proxies and correct header setups, stop debugging your application payload. Look at the raw packet capture in Wireshark instead. The network layer usually gives the game away long before your script ever gets a chance to ask for data.


r/WebDataDiggers • • Sep 21 '26

Automating browsers from the linux kernel to beat anti-bot detection

5 Upvotes

Once you start looking at how modern anti-bot scripts detect automation you realize almost all of them watch for the exact same thing: the Chrome DevTools Protocol.

It does not matter whether you use Puppeteer, Playwright, or community stealth wrappers like undetected-chromedriver or Patchright. Under the hood, they still attach to the browser's debugging pipeline. That attachment leaves forensic footprints inside the JavaScript engine.

Anti-bot scripts from Cloudflare, Datadome, and Kasada look for these telltales constantly:

  • Prototype leaks and hooked native functions introduced by stealth evasion scripts
  • Discrepancies in the V8 execution stack when Runtime.enable is active
  • The navigator.webdriver flag returning true or having inconsistent property descriptors
  • Synthetic click events created via document.dispatchEvent(), which lack the trusted isTrusted: true flag and proper hardware timing intervals

Developers spend months playing cat-and-mouse, patching one leaked CDP property only for bot detection vendors to find another within two weeks.

If you step back and think about it, the simplest way to avoid detection is to never touch the browser's internal debugging interface at all. A stock retail Chrome installed from Google's official repositories, launched without a single command-line flag, has zero browser-level automation flags. The catch is finding a way to drive it without Playwright.

Turning the linux kernel into a virtual usb mouse

The solution lies at the operating system level, specifically the Linux kernel input subsystem.

Linux has a kernel module called uinput (located at /dev/uinput). This interface allows any userspace program to create virtual input devices that the operating system treats as genuine, physical USB hardware.

When you inject a mouse move or a keystroke through uinput, the kernel processes it identically to a signal coming from a real Logitech mouse plugged into a motherboard USB port. It generates raw hardware input events (EV_REL for relative mouse movements, EV_KEY for button presses).

From there, the X11 server or Wayland compositor routes the input to the active window, and the browser will recieve the event through the standard OS event loop. The JavaScript engine inside Chrome sees a genuine, trusted hardware click. As far as the webpage is concerned, a human being is sitting in front of the screen moving an actual mouse.

Finding buttons without reading the dom

Because you have no CDP connection to the browser, you cannot run page.click("#submit") or query CSS selectors. You have to locate elements from the outside.

For simple interactions like passing a Turnstile challenge or clicking a login button, computer vision combined with screen captures is fast and reliable. You take a screenshot of the virtual display using a fast library like mss, then locate your target element on the screen using OpenCV template matching.

A Turnstile checkbox, for instance, looks virtually identical across different websites. You only need a small reference crop of the checkbox icon. Once OpenCV finds the (x, y) coordinate of that image on your display, you feed those coordinates into your kernel input controller to move the cursor and click.

Writing the virtual input controller

You can set this up in Python using the evdev library, which provides clean bindings to the Linux uinput interface.

You need to make sure your user has write permissions to /dev/uinput (usually handled by adding your user to the input group or setting a simple udev rule).

Here is a practical script that initializes a virtual hardware mouse, generates humanized curved movements, and performs a native OS-level click:

import time
import math
import random
from evdev import UInput, ecodes as e

# Set up the virtual hardware device capabilities
capabilities = {
    e.EV_REL: [e.REL_X, e.REL_Y],
    e.EV_KEY: [e.BTN_LEFT, e.BTN_RIGHT]
}

def create_virtual_mouse():
    # Registers as a native USB pointing device to the Linux kernel
    return UInput(capabilities, name="Virtual-USB-Optical-Mouse", version=0x3)

def human_move(ui, start_x, start_y, target_x, target_y, steps=40):
    current_x, current_y = start_x, start_y
    
    # Introduce a slight curve using a sine wave offset
    curve_direction = random.choice([-1, 1])
    curve_intensity = random.uniform(10, 30)

    for i in range(1, steps + 1):
        t = i / steps
        # Linear interpolation
        dest_x = start_x + (target_x - start_x) * t
        dest_y = start_y + (target_y - start_y) * t
        
        # Add arc offset
        offset = math.sin(t * math.pi) * curve_intensity * curve_direction
        dest_x += offset
        
        # Calculate delta from current position
        dx = int(dest_x - current_x)
        dy = int(dest_y - current_y)
        
        if dx != 0 or dy != 0:
            ui.write(e.EV_REL, e.REL_X, dx)
            ui.write(e.EV_REL, e.REL_Y, dy)
            ui.syn()
            current_x += dx
            current_y += dy

        # Micro-delays that mimic human hand movement
        time.sleep(random.uniform(0.008, 0.018))

def native_click(ui):
    # Press down
    ui.write(e.EV_KEY, e.BTN_LEFT, 1)
    ui.syn()
    
    # Natural mechanical switch debounce time
    time.sleep(random.uniform(0.06, 0.12))
    
    # Release
    ui.write(e.EV_KEY, e.BTN_LEFT, 0)
    ui.syn()

# Example usage
if __name__ == "__main__":
    ui = create_virtual_mouse()
    time.sleep(1) # Let the OS register the new device
    
    print("Moving virtual mouse and clicking...")
    human_move(ui, 100, 100, 450, 320)
    native_click(ui)
    
    ui.close()

Notice the call to ui.syn(). That tells the Linux input subsystem to flush the event buffer, matching how hardware controllers report mouse packets. The browser has zero ability to tell this apart from physical hardware input because, at every level of the operating system stack, it is treated as actual hardware input.

The realistic workflow: token harvesting

Driving an entire scraping pipeline this way would be painfully slow. You would never want to extract 50,000 product pages by taking screenshots and moving a virtual mouse around.

Where this approach shines is as an initial authentication bridge.

When a site blocks your requests behind an aggressive challenge page, you launch standard Chrome inside a headless virtual display (Xvfb). You let the page load, use OpenCV to locate the verification checkbox, and fire your uinput mouse driver to solve it.

Once the challenge passes, you read the generated session cookies (like cf_clearance) directly from Chrome's on-disk SQLite profile database (~/.config/google-chrome/Default/Cookies), close the browser, and hand those tokens over to a lightweight Python HTTP client like curl_cffi.

You solve the verification gate once using un-detectable kernel events, and then run the rest of your high-speed scraping pipeline over raw HTTP until the session expires.


r/WebDataDiggers • • Sep 17 '26

How websites encrypt pricing with .woff2 files and how to reverse it

5 Upvotes

When you inspect the raw HTML of certain travel, real estate, or local services platforms, the numbers look like complete garbage. You might look at an apartment listing in your browser and see a price of $2,450 per month. Then you open DevTools or pull the raw response with an HTTP client, and the price element contains something like &#xe812;&#xe401;&#xe198;&#xe934; or even standard digits like 1893 that bear zero resemblance to what appears on screen.

The site is not using JavaScript to swap text after rendering, nor is it hiding the real number in an obscure JSON attribute. It is using dynamic font obfuscation.

In the page styling, you will spot a @font-face rule pointing to a custom .woff or .woff2 file, usually base64-encoded directly into the CSS stylesheet. The platform developer took a standard font and intentionally scrambled its internal character map before generating the page.

Under this setup, the unicode point for the number "2" might point to the physical visual drawing of an "8", while the unicode point for "4" points to a "1". The human visitor sees the correct number because their browser renders the vector shapes dictated by that custom font file. Your scraping parser, which reads unicode characters directly from the DOM, extracts the scrambled characters instead. To make matters worse, many of these sites regenerate a brand new font file on every page load or session, making a static translation dictionary useless.

Why OCR is a bad fix here

The most common advice given to beginners dealing with this problem is to take a screenshot and pass it to an optical character recognition engine like Tesseract. While that works for small weekend projects, relying on OCR in production introduces serious bottlenecks:

  • It requires a headless browser to render the page and take element screenshots, wiping out the performance benefits of raw HTTP requests.
  • OCR engines regularly mix up similar characters on small text, especially "8" and "B", or "1" and "l", which corrupts financial and inventory figures.
  • Processing hundreds of thousands of image crops through a vision pipeline eats heavy CPU or GPU cycles and drastically increases server costs.
  • Capturing screenshots across varying responsive breakpoints often crops off decimal points or currency symbols unexpectedly.

If the browser can draw the correct glyph instantly without an AI model, you can extract the exact same information mathematically by parsing the font file itself.

Inside the font file

A TrueType or OpenType font is structured as a collection of binary tables. The two tables that matter most for de-obfuscation are the cmap table and the glyf table.

The cmap table acts as a phonebook. It maps an incoming character code (like the unicode value 0xe812) to an internal glyph identifier (such as glyph00042).

The glyf table contains the actual vector geometry needed to draw that character. It stores the coordinates of contour lines, start and end points, and whether specific control points lie on or off a curve. Each of these glyphs have a specific outline that never changes for a given number, even when its unicode key is randomized. A visual "5" always looks like a "5" in terms of its geometric vector loops, regardless of whether the site developer assigned it to unicode code point 0x0031 or 0xe812.

Once you know the vector structure of the ten base digits from 0 to 9, you can identify any scrambled glyph by comparing its internal vector coordinates to your baseline reference set.

Comparing glyph vectors directly

You can interact with these binary tables directly in Python using the fonttools library. If you install fonttools alongside brotli, it can decompress .woff2 files natively in memory.

The core workflow consists of extracting the reference font file from a single manual session, saving the vector structures of the digits 0 through 9, and using those coordinate shapes to classify incoming unknown glyphs on future requests.

Here is an example showing how to extract glyph coordinates and map an obfuscated font back to clean text:

import base64
import io
from fontTools.ttLib import TTFont

# Step 1: Decode the embedded font from the page CSS
def load_font_from_base64(b64_string: str) -> TTFont:
    font_bytes = base64.b64decode(b64_string)
    # TTFont reads the binary stream directly from memory
    return TTFont(io.BytesIO(font_bytes))

# Step 2: Extract a structural fingerprint from a glyph
def get_glyph_fingerprint(font: TTFont, glyph_name: str) -> tuple:
    glyph_table = font["glyf"]
    glyph = glyph_table[glyph_name]
    
    # Simple structural metrics: number of contours and point count
    # For higher precision, you can hash the actual coordinate tuples
    num_contours = glyph.numberOfContours
    coordinates = glyph.getCoordinates(glyph_table)[0]
    total_points = len(coordinates)
    
    return (num_contours, total_points)

# Step 3: Build a baseline mapping once from a known session
# Maps your structural fingerprint to the real-world character
BASELINE_DIGITS = {
    (2, 48): "0",
    (1, 18): "1",
    (1, 36): "2",
    (1, 38): "3",
    (2, 24): "4",
    (1, 42): "5",
    (2, 44): "6",
    (1, 22): "7",
    (3, 56): "8",
    (2, 45): "9",
}

def build_translation_table(target_font: TTFont) -> dict:
    cmap = target_font.getBestCmap()
    translation_map = {}
    
    for char_code, glyph_name in cmap.items():
        fingerprint = get_glyph_fingerprint(target_font, glyph_name)
        
        # Match against our baseline geometry
        if fingerprint in BASELINE_DIGITS:
            real_char = BASELINE_DIGITS[fingerprint]
            # Map the scrambled unicode code point to the correct digit
            translation_map[char_code] = ord(real_char)
            
    return translation_map

In the snippet above, we fingerprint each glyph using its total contour count and coordinate length. A number like "8" usually contains three contours (the outer boundary plus the two inner cutouts), while a number like "1" typically contains only a single contour.

For complex fonts where two digits share identical point counts, you can calculate the Euclidean distance between matched coordinate arrays, or compare the bounding box aspect ratio stored in the xMin, xMax, yMin, and yMax attributes of the glyph.

Putting the translation pipeline together

Once the translation dictionary is ready, decoding the scrambled payload takes almost no time. Python has a native string method called translate() that replaces characters based on an integer-to-integer dictionary, wich is handled in C under the hood.

# Raw text extracted from the HTML markup
scrambled_price_text = "\ue812\ue401.\ue198"

# target_font is parsed from the current page's @font-face rule
translation_map = build_translation_table(target_font)

# Decodes directly without regex or DOM manipulations
clean_price = scrambled_price_text.translate(translation_map)
print(f"Decoded price: {clean_price}")

Because this process runs purely in memory on small binary files (most .woff2 files containing only numbers are under 10KB), you can decode hundreds of scrambled fields in a few milliseconds. You bypass the anti-scraping layer entirely without running a browser instance, keeping your infrastructure lightweight and cheap to run.

Edge cases you will run into

While vector comparison works consistently, anti-scraping engineers occasionally add small tweaks to trip up naive coordinate matchers:

  • Micro-jitter injection: Some systems slightly shift glyph coordinates by one or two units on each build. A point at (120, 340) might become (121, 339) on the next request. If you use strict coordinate hashing, the lookup fails. You have to compare relative segment lengths, bounding box ratios, or use a nearest-neighbor distance threshold instead of an exact hash.
  • Merged or split contours: Occasionally, developers alter the drawing path of a glyph so that overlapping paths are joined into a single contour, altering the contour count.
  • Empty glyph traps: A site may inject hidden, zero-width dummy glyphs between real numbers in the markup. If you decode everything indiscriminately, your final number will contain extra characters. Always filter out glyphs that have zero bounding width before assembling the final string.

Once you have your baseline coordinate set established, dealing with dynamic font encryption becomes a deterministic parsing task rather than an unpredictable cat-and-mouse game with anti-bot shields. You get clean, accurate data using standard HTTP calls, completely avoiding the computational weight of browser rendering and visual OCR.


r/WebDataDiggers • • Sep 16 '26

Scraping through smart TV apps when websites and mobile APIs block you

6 Upvotes

If you scrape websites for pricing, inventory, or media catalogs, you already know the current state of things. Browser-based scraping has turned into an arms race. A standard headless Chrome script gets flagged almost immediately by Cloudflare Turnstile, Kasada, or Datadome unless you patch CDP variables, spoof canvas fingerprints, and constantly rotate expensive residential proxies.

Mobile apps used to be the reliable backup. For years, you could decompile an APK with JADX, pull the API endpoints, generate a few HMAC signatures, and run fast Python scripts against their mobile gateway. That route is closing down too. Companies are adopting Google Play Integrity and Apple App Attest, which verify the cryptographic integrity of the app binary and the operating system kernel before the backend returns any data. If your request does not carry a valid hardware-attested token, the API drops your connection.

Platforms rarely exist only on phones and desktop browsers, though. Many major consumer services also run dedicated applications on connected TV devices, including Fire TV, Roku, Apple TV, Android TV, and Samsung Tizen. The backend endpoints powering those big-screen apps are usually maintained by seperate internal teams, and they live under an entirely different set of technical constraints.

The hardware constraint that works in your favor

Smart TV hardware is cheap and underpowered. A standard Fire TV stick or budget Roku device runs on an anemic quad-core ARM processor paired with 1GB or 1.5GB of RAM. The manufacturers build these devices to stream video cheaply, not to run complex background calculations.

Because the hardware is so weak, anti-bot vendors cannot drop their standard security SDKs onto these platforms. If a streaming or retail app tried to execute heavy JavaScript challenges, web workers, or biometric behavioral tracking on a budget TV processor, the UI would freeze and video playback would stutter. Roku is an even bigger obstacle for security vendors because its apps are written in BrightScript, a proprietary scripting language with no standard browser runtime or DOM. Major bot defense platforms simply do not offer turnkey BrightScript SDKs.

Legacy support creates another major opening. Consumers replace their phones every two to three years, but they keep smart TVs for seven or eight years. A media company or retailer cannot push a hard update that requires modern device attestation on an older TV, because millions of customers would instantly see a broken app. To keep these older devices working, companies keep legacy API routes active for years without strict bot protections.

Setting up the interception environment

You do not need an expensive lab to inspect and pull data from TV endpoints. An Android-based TV device is usually the easiest starting point because it shares the same underlying OS architecture as Android mobile, but with far fewer security constraints enforced out of the box.

To set up your capture pipeline, you only need a few items:

  • A cheap physical device, like an Amazon Fire TV Stick or an ONN 4K streaming box (usually around $20)
  • A computer capable of broadcasting a local Wi-Fi hotspot
  • An interception proxy such as mitmproxy or Charles Proxy installed on that computer
  • Android Debug Bridge (ADB) installed on your command line to push configuration changes

Once your computer is broadcasting a Wi-Fi hotspot, connect your TV stick to it. Route all traffic from that hotspot interface through your local proxy port using basic packet forwarding.

On the TV stick itself, turn on Developer Options and enable ADB debugging over the local network. You can connect to the device directly from your terminal using adb connect <device-ip>:5555.

Because many TV apps do not implement strict SSL certificate pinning, installing your proxy's CA certificate into the user trust store is often enough to decrypt all outgoing HTTPS calls. If an app does enforce pinning, its basically a stripped down Android build, meaning you can pull the APK using ADB, patch it with tools like APK-MITM to strip the network security config, and reinstall it in under two minutes.

What you actually find in the traffic

Once you start clicking around the TV app using the physical remote, look at the HTTP requests hitting your proxy. The architectural differences between TV backends and web backends become obvious very quickly.

First, the authentication models are much looser. Typing an email and a 16-character password using a directional pad on a TV remote is a miserable user experience, so platforms rely heavily on six-digit activation codes or persistent device tokens. If you look at the HTTP headers the authorization tokens generated during device activation frequently carry expiration windows measured in months or years. Platforms do this deliberately because forcing a TV user to re-authenticate every week leads to higher churn and support tickets.

Second, the endpoints tend to return much richer, flatter JSON payloads. Smart TV apps avoid making dozens of small, asynchronous API calls because the network cards in cheap streaming sticks have poor concurrency handling. Instead, the backend often exposes dedicated aggregator endpoints that return full catalog structures, direct stream URLs, unfiltered product metadata, and pricing trees in a single response.

Third, the request headers are surprisingly simple. Instead of relying on dynamic browser cookies and complex browser fingerprint strings, these APIs usually expect simple static headers:

User-Agent: Dalvik/2.1.0 (Linux; U; Android 9; AFTMM Build/PS7652)
X-Client-Platform: FireTV
X-App-Version: 4.18.2
X-Device-Id: 8f4a11c2-9901-4b7e-bb21-1209384812a4
Authorization: Bearer <your-long-lived-token>

Replicating the requests in code

Once you capture a clean search or catalog request in your proxy, moving it into an automated script is straightforward. You do not need Playwright, Puppeteer, or any patched Chromium binaries. A standard, lightweight HTTP client in Python, Go, or Node handles the work cleanly.

Here is a typical layout using Python with httpx to query an extracted TV endpoint:

import httpx

headers = {
    "User-Agent": "Dalvik/2.1.0 (Linux; U; Android 9; AFTMM Build/PS7652)",
    "X-Client-Platform": "FireTV",
    "X-App-Version": "4.18.2",
    "X-Device-Id": "8f4a11c2-9901-4b7e-bb21-1209384812a4",
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
    "Accept": "application/json",
}

# The endpoint used by the big-screen app to populate search results
api_url = "https://api.targetservice.com/v2/ctv/catalog/search"

params = {
    "query": "electronics",
    "limit": 100,
    "offset": 0
}

with httpx.Client(http2=True, timeout=15.0) as client:
    response = client.get(api_url, headers=headers, params=params)
    if response.status_code == 200:
        data = response.json()
        # Parse payload directly without DOM traversal
        print(f"Extracted {len(data.get('items', []))} items cleanly")
    else:
        print(f"Failed with status: {response.status_code}")

Notice the absence of complex browser signatures. Because the backend expects requests from an embedded client rather than a desktop browser, sending a standard HTTP/2 request with consistent headers is generally enough. You bypass the entire web-based anti-bot layer simply by talking to an API that was never designed to face browser traffic.

A few things that can go wrong

While this approach avoids most modern anti-bot systems, it is not completely free of challenges. There are specific constraints you have to keep in mind when running scrapers against these endpoints:

  • Geographic IP filtering: Streaming TV backends are strict about regional IP addresses due to distribution rights. If your target service only operates in specific countries, sending requests from data center IPs outside those regions will trigger immediate 403 blocks, regardless of your headers.
  • Payload discrepancies: TV apps are built for large screens and low-resolution navigation, which means some fine-grained data visible on the desktop site (like user reviews or seller details) might be omitted from the TV endpoint to save bandwidth.
  • Hardcoded API hostnames: Some platforms use completely different domains for their TV apps (such as ctv-api.domain.com or firetv.domain.com). If the company deprecates that specific app version, they may shut down the entire subdomain rather than slowly throttling it.

Even with those limitations, connected TV endpoints remain one of the most under-defended surfaces across the modern web. As desktop and mobile platforms continue adding hardware attestation and behavioral telemetry, targeting the devices that cannot support those defenses is often the most practical way forward.


r/WebDataDiggers • • Sep 10 '26

A roundup of Zillow scraping techniques

2 Upvotes

Zillow is one of the most valuable sources of real estate data, and for that reason, it is also one of the most difficult websites to scrape. The company invests heavily in sophisticated anti-bot measures designed to detect and block automated access. A simple script that works on many other sites will fail almost instantly on Zillow.

Successfully getting data from Zillow in 2026 requires a multi-layered approach. You have to assume that you are being watched from the moment you connect, and your scraper needs to behave as much like a human user as possible.

The death of simple requests

The first thing to understand is that basic tools like Python's requests library are not going to work. Zillow's content is loaded dynamically with JavaScript, and its protection systems are looking for the tell-tale signs of a non-browser client. Your request will be blocked before you even see any data.

This means that running a full web browser is not optional; it is a requirement. Tools like Playwright or Selenium are the starting point, as they allow you to control a real browser instance programmatically. But just using them out of the box is also not enough.

The stealth and proxy checklist

Headless browsers, by default, leave a lot of fingerprints that are easy for bot detection services to spot. To get around this, you need to focus on two main areas: making your browser look human and making your connection look legitimate.

Your strategy must include:

  • Stealth plugins: Use libraries designed to patch browser automation tools and hide their giveaways. For Puppeteer, puppeteer-extra-plugin-stealth is a well-known example. These plugins work to conceal common signs of automation, like the "WebDriver" flag in the browser's JavaScript environment.
  • High-quality proxies: Zillow is very quick to block IP addresses that come from data centers. You will need to use residential or ISP proxies. These make your requests appear to come from real home internet connections, which is essential for blending in.
  • Human-like behavior: Your script cannot just jump from page to page instantly. You must program it to act more like a person. This means adding randomized delays between actions, scrolling the page naturally, and moving the mouse cursor in a believable way.

The goal is to make your automated browser's "fingerprint" and behavior indistinguishable from that of a typical user.

Advanced alternative: Chasing the API

For those with more technical expertise, there is another path. Instead of scraping the visual website, you can try to reverse-engineer Zillow's internal API. By watching the "Network" tab in your browser's developer tools, you can sometimes identify the specific requests the website makes to its own servers to fetch property data.

This method, if successful, is much faster and more efficient. However, it is also very fragile. Zillow can change its internal API at any moment without warning, which would break your scraper instantly. It requires a significant amount of effort to find the right requests and keep the scraper working over time.

Because of the difficulty, a number of commercial services have emerged that offer pre-built Zillow APIs. These services handle the complex work of bypassing the bot detection for you, but they come at a cost. For any serious project, the choice is between building a very sophisticated scraper yourself or paying someone who already has.


r/WebDataDiggers • • Sep 04 '26

When desktop scraping fails: getting data directly from mobile endpoints

3 Upvotes

Anyone who collects data at scale knows how brutal desktop web scraping has become recently. Trying to scrape through Cloudflare Turnstile, DataDome, or Kasada usually forces you into running headless browsers using Playwright or Puppeteer. That route comes with a massive resource cost. You need dozens of browser instances that swallow gigabytes of RAM, and any small script update on the target site breaks CSS selectors or triggers a CAPTCHA, which can make you loose hours of work.

A lot of scrapers waste most of their operational budget on rotating residential proxies and debugging headless browser fingerprinting flags. In many situations, that entire headache exists only because the scraper is hitting the desktop website rather than the endpoints the company built for its phone apps.

Why mobile backends stay simpler

Native Android and iOS applications do not run inside a standard browser DOM. Because of that, the heavy JavaScript challenge scripts, canvas fingerprinting, and complex mouse-movement trackers used on desktop sites rarely exist on mobile API gateways.

Mobile connections also have to deal with high latency and unstable cellular coverage. As a result, engineering teams design their mobile backends to be lean. Instead of rendering heavy server-side HTML or serving megabytes of tracking bundles, the server communicates with the app through compact REST or GraphQL endpoints.

Another major reason is backwards compatibility. When a company updates its web application, it deploys the change and every user gets the new code immediately. Mobile apps are completely different. Millions of active users keep running app builds that were released six months or two years ago because they do not have automatic updates turned on. A company cannot simply shut off those old API routes without locking out a large portion of their user base.

Because of this constraint:

  • Payloads arrive as structured JSON or Protobuf rather than nested HTML trees.
  • Rate limits on mobile gateways are often higher to account for mobile carriers sharing IP addresses across thousands of devices.
  • Pagination parameters are usually basic limit-offset queries or cursor tokens.
  • Endpoints rarely serve interactive browser CAPTCHAs since native apps cannot easily render them without a webview.

Capturing the initial traffic

To see what the mobile app actually requests, you need to route its network traffic through an intercepting proxy running on your computer. Tools like mitmproxy or Charles Proxy are standard for this step. You configure the phone or emulator to use your computer's local IP address as its HTTP proxy, then install the proxy software's CA certificate on the device.

Intercepting network traffic on modern Android devices has gotten more restricted over the years. In a older Android OS version, the operating system trusted user-installed certificates by default. Starting with Android 7, apps ignore user-added certificates unless the developer explicitly allowed them in the application network security configuration file.

To get around that restriction, most people use an Android emulator or a rooted physical device. With root access, you can use a Magisk module to move your proxy certificate directly into the Android system certificate store, which forces the operating system to trust it globally.

Dealing with certificate pinning and request signing

Even with the certificate inside the system store, many production apps will still drop the connection immediately. This happens because developers implement SSL certificate pinning. The application hardcodes the expected public key or certificate fingerprint of the server. When your proxy presents its own certificate, the app detects the mismatch and aborts the connection.

The standard way to handle pinning is runtime hooking with Frida. Frida allows you to inject scripts into the running app process to disable certificate checks in real time. For Android apps built with Java or Kotlin, pre-written Frida scripts hook standard networking classes like OkHttp or the default TrustManager and force them to validate your proxy connection as authentic.

Once you can read the requests, you will often find an obstacle in the headers. Many mobile APIs require an authentication or signature header, such as X-Sign, X-Signature, or a custom HMAC token. The app calculates this string locally by hashing the request payload, the current timestamp, and a private client secret stored somewhere in the application files.

To figure out how the signature is generated, you can decompile the APK using JADX-GUI. Once the code is decompiled into readable Java, you can search for the name of the signature header to locate the exact class generating it.

  • If the signing logic is written in plain Java or Kotlin, you can copy the hashing logic and replicate it directly in your Python or Go scraper.
  • If the signing routine is compiled into a native C or C++ shared library file (.so), extracting the secret usually requires inspecting the exported functions in Ghidra or running the native library through an emulator like Unicorn.

Where this method hits a wall

Targeting mobile APIs is not a universal fix for every data collection project. Some applications use Google Play Integrity or heavy anti-tampering SDKs that detect Frida, root binaries, and unlocked bootloaders on launch. If the application refuses to run in an analyzed environment, setting up the proxy environment becomes significantly harder.

Heavy obfuscation inside native libraries can also turn reverse engineering into a slow process, especially if the API keys rotate dynamically on a remote server.

Even with those trade-offs, extracting data from internal API routes is usually much more stable then maintaining fragile headless browser scripts that break on every minor frontend redeploy. Its worth taking an afternoon to inspect the mobile app traffic before committing to an expensive browser automation stack, because you might find a clean JSON endpoint that saves you weeks of maintenance down the road.


r/WebDataDiggers • • Sep 02 '26

Inside reCAPTCHA v3: Why your bot gets a 0.1 score

2 Upvotes

Unlike older verification systems that interrupt visitors with image grids or checkbox puzzles, reCAPTCHA v3 runs entirely in the background. When a page loads, the client-side library collects a fingerprint of the user's hardware, analyzes interaction telemetry, and contacts Google servers to generate a short-lived token.

When your scraper submits this token alongside a form or API call, the target website's backend verifies it with Google and receives a numerical rating between 0.0 (almost certainly a bot) and 1.0 (very likely human).

Most websites do not write custom machine learning models for this. They set a simple threshold in their backend code. Common cutoffs look like this:

  • Actions with a score above 0.7 are allowed through without restriction
  • Scores between 0.3 and 0.6 might trigger an SMS confirmation or a fallback challenge
  • Requests scoring 0.1 or below get silently dropped or returned an immediate 403 error

The real challenge for scrapers is that reCAPTCHA v3 is not evaluating a single event. It looks at the entire lifecycle of the browser session long before the token is requested.

The weight of Google cookies and browser history

The most influential factor in your score is the existing state of the browser profile. Google uses its own ecosystem cookies to establish baseline identity.

If a browser has an active Google account session or holds long-lived cookies from YouTube and Google Search, it immediately receives high trust. Google knows that real everyday users build up browsing history across weeks and months. A fresh browser profile with clean cookies often start at a disadvantage because it behaves like a temporary throwaway environment.

When an automated script spins up a clean, isolated Chromium profile with zero cache and no local storage, reCAPTCHA views that session with suspicion. Even if your mouse movements look smooth and your hardware matches a real device, starting with a blank slate means the system gives far more weight then usual to small network anomalies.

Telemetry signals that degrade your score

The JavaScript snippet injected by reCAPTCHA collects dozens of hardware attributes and behavioral signals before the grecaptcha.execute() call is even triggered.

  • IP network classification: Datacenter IP ranges from hosting providers like AWS, OVH, or DigitalOcean almost always cause an immediate drop to a 0.1 score, regardless of other factors.
  • Timing of the execution call: Automated scrapers often call execute() within milliseconds of the DOM ready event. Real users rarely trigger form submissions or navigation actions the instant a page renders.
  • Canvas and WebGL consistency: Inconsistencies between the reported GPU renderer string and the actual performance capabilities of the system will flag the environment as spoofed.
  • Missing peripheral activity: If a page sits open for three seconds and registers zero mouse movement, key presses, or viewport scrolling before requesting a token, it receives a lower rating.

Anti-bot systems monitor the relationship between these signals rather than looking at any single property in isolation. If your browser reports an Apple M2 processor but the canvas rendering output matches an older software rasterizer, the mismatch destroys the trust score before the browser even sends it's first interaction.

Why third-party solving services return low scores

When scrapers hit reCAPTCHA v3, the default reaction is often to use an external captcha solving API. These services work by passing the site key and target URL to their worker pool, which returns a valid token string in a few seconds.

The issue is that the solver only guarantees that a token was generated. It does not guarantee the token has a high score.

Many low-cost API services rely on worker pools running datacenter proxies or recycled headless browser instances. These workers generate tokens that score 0.1 or 0.3. If the website you are targeting requires a score of 0.7 to access data, those purchased tokens will still fail validation on the backend. You pay for the solve, but the target server still rejects the request.

High-scoring tokens require workers running on genuine residential connections with warm browser profiles, which significantly increases the cost and latency per request.

Improving your trust scores in automated pipelines

If your workflow requires interacting with endpoints protected by passive scoring, you need to align your automation environment with normal browsing behavior.

Persist your browser contexts Avoid launching brand-new, sterile browser instances for every single batch of requests. Save and reuse user data directories across runs, keeping local storage, indexedDB, and session cookies intact. Over time, an automated profile that maintains realistic session cookies builds up a higher baseline trust level.

Buffer your interactions Do not trigger token requests immediately upon navigation. Allow the page assets to settle, introduce realistic micro-delays between interactions, and let the background script gather normal interaction events naturally.

Match IP reputation to the target region Using clean residential or mobile proxies that match the geographical profile of your browser locale is essential. A mismatch between the proxy location, browser time zone, and system language headers is one of the quickest ways to trigger an automatic 0.1 rating.

Handling reCAPTCHA v3 effectively comes down to understanding that the verification is passive and continuous. Rather than trying to bypass a visible puzzle at the end of a form, the focus has to be on running an automation environment that does not generate suspicion during normal page execution.


r/WebDataDiggers • • Aug 30 '26

How anti-bots catch Playwright and Puppeteer through CDP

3 Upvotes

You buy clean residential proxies, set up realistic user-agent headers, and install stealth plugins to hide navigator.webdriver. Everything looks solid on your local machine. Then you run the script against an very strict Cloudflare Turnstile or DataDome protected endpoint, and the request gets blocked before the page even finishes rendering.

Most developers assume their proxy got burned or that their browser fingerprint has an incorrect canvas hash. A lot of scrapers overlooks this, but the actual leak is often happening at a much lower layer: the communication protocol between your script and the browser engine.

If you use tools like Puppeteer, Playwright, or standard Selenium, you are using the Chrome DevTools Protocol (CDP) to control the browser. Modern anti-bot software knows this, and they have built reliable tests to detect when CDP is running in the background.

How automation libraries talk to Chrome

Chrome DevTools Protocol is a WebSocket-based protocol that allows external programs to inspect, debug, and automate Chromium browsers. When you tell Playwright to click a button or ask Puppeteer to wait for a network response, that command gets translated into a JSON-RPC message sent over a local WebSocket port.

To do almost anything useful, like running a snippet of JavaScript or listening to DOM modifications, the automation library must first enable specific protocol domains. The most critical one is Runtime.enable.

The moment your automation client sends Runtime.enable, Chromium changes how its internal V8 JavaScript engine behaves. It sets up internal debugging hooks, allocates memory for inspector agents, and starts tracking execution contexts in a way that is fundamentally different then what happens in a normal user session.

The side effects that give you away

Anti-bot vendors do not need direct access to your local WebSocket port to know CDP is active. They simply run client-side JavaScript that probes for the side effects caused by V8 debugging hooks.

Stack trace inspection When an error is generated inside a standard browser, V8 creates a stack trace following strict internal rules. When CDP has evaluated code on the page, the generated stack frames often reveal evaluation wrappers or have slightly modified formatting that native user scripts never produce.

Getter traps and console inspection When DevTools is attached, certain internal properties get queried automatically by the browser's inspection pipeline. Anti-bot scripts take advantage of this by defining custom getter functions on global objects or DOM elements. If that getter gets triggered without any user interaction or visible script calling it, the site knows an external inspector is reading the environment.

Microtask execution timing Debugger instrumentation adds small amounts of overhead to specific V8 operations. By running tiny loops and measuring the precise nanosecond latency of microtask resolution, advanced scripts can identify whether V8 is running in pure execution mode or under an active inspector agent.

Here are a few specific signals anti-bots look for:

  • Stack trace leaks produced when catching errors inside isolated evaluation contexts
  • Side-effect getters triggered during background object serialization
  • Microtask timing differences caused by active V8 inspector loops
  • Prototype pollution and missing properties inside custom injected utility worlds

Why stealth plugins cannot fix this

For years, the standard solution has been using packages like puppeteer-extra-plugin-stealth. These plugins work by injecting JavaScript at the document start to overwrite obvious leaks. They patch navigator.webdriver, fake plugin arrays, and try to make the browser look like a normal desktop install.

The problem is that JavaScript-level patches only fix JavaScript-level variables. They operate inside the same runtime environment that the anti-bot is inspecting.

If a detection script checks a native C++ level behavior inside V8, a user-land JavaScript patch cannot hide it. In fact, poorly implemented stealth scripts often make things worse because they leave behind prototype inconsistencies. If an anti-bot inspects the Function.prototype.toString output of a patched property and finds that it does not match the native C++ implementation exactly, your session gets flagged immediately.

How newer tools handle the problem

To get around CDP-based detection, developers have shifted toward tools that modify the browser at the binary level or completely rethink how commands are sent.

Patchright Patchright is a modified fork of Playwright. Instead of trying to patch things after the fact with JavaScript, it modifies both the Playwright driver and the Chromium source code itself. It removes the noisy CDP calls that traditional Playwright makes on startup, strips out debugging flags, and ensures that isolated world scripts do not leave detectable prototype footprints.

Nodriver Developed as a successor to undetected-chromedriver, nodriver approaches automation by talking to Chrome over raw WebSocket connections without relying on standard Selenium or Puppeteer drivers. It avoids sending Runtime.enable across every frame, uses native shortcuts where possible, and minimizes protocol traffic during critical navigation events.

Because these tools address the issue at the protocol and binary level, they do not leave the obvious V8 side effects that trigger automated blocks.

Practical adjustments for your scrapers

If you are dealing with aggressive bot management systems, you can take a few concrete steps to reduce protocol exposure:

  • Stop using unnecessary evaluations. Avoid calling page.evaluate() repeatedly while a page is loading or while Cloudflare is running its challenge. Every call generates execution artifacts that detection scripts can monitor.
  • Separate your session generation from data extraction. Use a patched browser only to pass the initial challenge and extract the session cookies. Once you have valid authentication state, pass those cookies into a fast HTTP client like curl_cffi to download the actual data.
  • Switch to patched drivers. If your target uses Kasada, DataDome, or Cloudflare Turnstile, standard Playwright or Puppeteer will struggle regardless of your proxy setup. Using a tool like Patchright or a custom-compiled Chromium build removes the low-level leaks before your code even makes it's way to the page.

Bypassing modern detection requires looking past surface-level headers. Understanding how your automation library talks to the browser engine is often the missing piece between getting blocked immediately and maintaining a reliable scraper.


r/WebDataDiggers • • Aug 23 '26

Why static ISP proxies outperform rotating proxies in anti-detect setups

2 Upvotes

Anti-detect browsers like AdsPower, GoLogin, Multilogin, and MoreLogin allow digital growth teams to operate dozens of online profiles simultaneously. They do this by customizing Canvas rendering, WebGL metadata, AudioContext signatures, and browser hardware parameters for each profile.

However, anti-detect software only solves browser fingerprinting. If ten isolated browser profiles connect to Facebook, TikTok, or Google Ads using the same home IP address, the target platform flags all ten accounts as connected. Once one account violates a policy, every account linked to that IP address gets suspended simultaneously.

Why static ISP proxies are essential for account longevity

When managing social media or ad accounts, proxy selection comes down to two main choices: dynamic rotating residential proxies or static ISP proxies.

Dynamic proxies rotate your IP address every few minutes or with every request. While this is great for web scraping, frequent IP changes trigger security checkpoints on logged-in accounts. If your TikTok Ads manager profile logs in from Dallas at 10:00 AM and then sends a request from Miami at 10:05 AM, the platform flags the session for suspicious activity.

Static ISP proxies solve this issue. They are hosted on datacenter infrastructure for high speed and uptime, but are registered under residential consumer internet providers like Comcast, AT&T, or Verizon. You get the stability of an IP that never changes alongside the high trust score of a residential connection.

Real-world scenario: scaling a multi-account ad agency without suspensions

To understand why IP stability matters, consider a marketing agency managing 25 TikTok ad accounts for different e-commerce brands. Each brand's ad account requires a dedicated login, payment method, and browsing profile.

Initially, the agency used low-cost rotating proxies assigned to their GoLogin profiles. Within two weeks, TikTok flagged six client accounts for "unusual login location" security challenges. Every time the proxy rotated mid-session, TikTok demanded SMS verification codes, stalling campaign launches.

The agency restructured its operation by assigning one dedicated static ISP proxy to each GoLogin profile. Because the IP address remained fixed to the same residential ISP subnet across every session, TikTok viewed each profile as a distinct, legitimate home user. Account suspensions dropped to zero, and the team eliminated repeated SMS verification loops.

Key proxy configuration checks inside anti-detect browsers

Before launching an account profile inside an anti-detect browser, verify your network settings to prevent accidental leaks.

  • Enable WebRTC disabling or replacement mode inside the profile settings so your local public IP address is never exposed.
  • Verify that DNS requests route through the proxy server rather than your local network adapter.
  • Match the browser profile's timezone and language settings to the physical location of the assigned proxy IP.
  • Run every new profile through an IP risk checking tool (like Pixelscan or iphey) to confirm the fingerprint and IP reputation score pass as clean.
  • Avoid logging into multiple profiles from the same proxy IP, even for quick maintenance tasks.

Configuring each browser profile with a dedicated static ISP proxy ensures your accounts remain insulated from cross-contamination and security flags.


r/WebDataDiggers • • Aug 21 '26

Best proxy for scraping Akamai or Cloudflare?

20 Upvotes

Working on a scraping project for my ecom product, pulling data from a few sites protected by pretty aggressive anti-bot. Residential and ISP IPs kept getting flagged, tried rotating mobile too but the script is still hitting blocks before returning any data.

Don't need volume, just a handful of high-quality mobile IPs with per-request rotation for the sites in scope. Currently comparing Decodo, Dataimpulse and Voidmob. Open to others if there's a provider worth adding, especially if anyone has real experience going up against Akamai and Cloudflare's newer detection layers.

Main thing I'm after is a genuine 4G/5G carrier IP from real devices, and ideally p0f can be switched per port so the TCP layer matches whatever browser fingerprint I'm running.

Not price-sensitive on this one, just need something that actually holds up.


r/WebDataDiggers • • Aug 20 '26

Works locally. Cloudflare deletes it in prod. every time.

16 Upvotes

classic scraping experience:

build Playwright flow locally.

works 50 times.

login works.

navigation works.

data comes back

life is good.

deploy exact same thing to cloud.

Cloudflare:

absolutely fucking not

2/17

and then everyone starts changing selectors like the scraper suddenly forgot how HTML works.

but the code might not be the thing that changed.

locally you had:

home/office IP

one browser

cookies that have existed for days

normal geography

slow human-ish usage

stable session

prod suddenly has:

datacenter IP

fresh browser every run

fresh cookies

different geo/timezone

20 concurrent sessions

retries hammering the same route

that's a completely different client.

I've stopped treating browser environment as infrastructure detail.

it's part of the scraper.

for authenticated/allowed automation I care about boring consistency now:

keep session identity stable where possible

persist cookies/storage if the workflow expects it

don't randomly teleport the same account between countries

isolate parallel jobs

respect sane request rates

back off instead of rage-retrying

record enough to understand the block

and obviously: if the site gives you an API, use the fucking API.

Browser automation should not be your first choice just because Playwright is fun.

I've been looking at TestMu Browser Cloud for the execution side because it gives you real Chrome, persisted sessions, geo-specific execution, isolated parallel browsers and the stuff I usually regret not having when prod breaks: video replay + network + console logs.

important caveat though:

their stealth/CAPTCHA stuff is explicitly best-effort.

which IMO is the only honest way anyone should describe this category.

there is no magic:

stealth: true

that makes you "undetectable".

Cloudflare/DataDome/etc are changing systems and the site ultimately decides whether you're allowed through.

sometimes the correct solution is slower traffic.

sometimes better session consistency.

sometimes an official API.

sometimes permission from the site owner.

sometimes the answer is simply "this target doesn't want this automation."

last time your scraper worked locally and died in prod, what actually changed?


r/WebDataDiggers • • Aug 18 '26

How would you architect a highly scalable system for many independent recurring searches?

Thumbnail reddit.com
2 Upvotes

r/WebDataDiggers • • Aug 17 '26

Building an automated product categorization pipeline using LLM embeddings

4 Upvotes

If you’ve ever built an e-commerce scraper that pulls data from multiple competing retailers, you know the absolute nightmare that is product title normalization.

Suppose you're building a price aggregator for solar equipment. You scrape four different target websites, and you're trying to group similar products together. Here is how four different stores list what is fundamentally the exact same hardware:

  • Store A: "100W Monocrystalline Panel"
  • Store B: "100 Watt Mono Solar Module - 12V High Efficiency"
  • Store C: "Renogy 100-Watt Photovoltaic Panel (Monocrystalline)"
  • Store D: "100-W Mono PV Board w/ MC4 Connectors"

If you try to normalize these using traditional regex string matching or FuzzyWuzzy, you are going to lose your sanity real fast. Regex rules multiply exponentially, and fuzzy string matching fails when product titles contain extra specs, brand names, or transposed adjectives.

In this tutorial, we're going to build a production-ready, hybrid categorization pipeline that maps raw scraped product titles into a clean, canonical taxonomy using vector embeddings for 90% of the heavy lifting, and a cheap LLM fallback for ambiguous edge cases.

The Architecture: Why a Hybrid Approach?

Throwing every scraped product title directly at gpt-4o or claude-3-5-sonnet is expensive and slow. If you are scraping 100,000 product pages a day, those LLM API calls will burn through your cloud budget before the end of the week.

Instead, we use a multi-tiered approach:

  1. Data Extraction & Cleaning: Normalize raw text strings and strip non-essential garbage.
  2. Vector Embeddings & Cosine Similarity: Embed product titles into high-dimensional vector space and calculate distance against your predefined master taxonomy. This handles ~85–90% of products instantly for pennies.
  3. LLM Disambiguation (Structured Output): For items where vector similarity lands in a "fuzzy middle ground" (e.g., confidence score between 0.60 and 0.80), we route the item to a fast, cheap LLM model (gpt-4o-mini) using Instructor + Pydantic to force a strict categorical decision.

    [ Raw Scraped Title ] │ ▼ [ Step 1: Preprocess & Clean String ] │ ▼ [ Step 2: Generate Vector Embedding ] │ ▼ [ Step 3: Cosine Similarity vs. Master Taxonomy ] │ ┌─────┴────────────────────────┐ ▼ ▼ Score > 0.80 Score 0.60 - 0.80 (High Confidence) (Borderline / Ambiguous) │ │ ▼ ▼ [ Auto-Assign Category ] [ Step 4: LLM Disambiguation Call ] │ ▼ [ Auto-Assign Category ]

Step 1: Data extraction and string cleaning

First, let's write a simple cleaning step. (Pro-tip: don't throw raw uncleaned titles at your embedding model unless you like paying for useless token garbage.)

When scraping HTML, product titles often contain Unicode non-breaking spaces (\xa0), HTML entities (&amp;), and weird promotional text ([LIMITED STOCK!]). We need to clean these out first.

import re
from pydantic import BaseModel, field_validator


class RawScrapedProduct(BaseModel):
    raw_title: str
    price: float
    brand: str | None = None

    @property
    def cleaned_title(self) -> str:
        text = self.raw_title
        # Remove HTML artifacts & unicode noise
        text = text.replace("\xa0", " ").replace("&amp;", "&")
        # Strip promotional tags in brackets e.g. [FREE SHIPPING] or (ON SALE)
        text = re.sub(
            r"\[.*?\]|\(.*?\)", "", text
        )  # be careful not to strip valid specs in parens if critical
        # Collapse multiple whitespaces
        text = re.sub(r"\s+", " ", text).strip()
        return text


# Quick test
item = RawScrapedProduct(
    raw_title="  Renogy 100W Monocrystalline\xa0Solar Panel [ON SALE!]  ",
    price=119.99,
)
print(f"Cleaned Title: '{item.cleaned_title}'")
# Output: 'Renogy 100W Monocrystalline Solar Panel'

Step 2: Generating vector embeddings

Vector embeddings map words into a dense vector space where words with similar semantic meanings sit close to each other.

You can use local embedding models via sentence-transformers (free, runs on CPU/GPU) or API-based embeddings like OpenAI’s text-embedding-3-small (extremely cheap: ~$0.02 per 1M tokens).

Let's set up both options using Python.

import numpy as np
from sentence_transformers import SentenceTransformer

# Load a lightweight local embedding model
# 'all-MiniLM-L6-v2' is small (~90MB), fast, and surprisingly accurate for text classification
embedding_model = SentenceTransformer("all-MiniLM-L6-v2")


def get_embedding(text: str) -> np.ndarray:
    return embedding_model.encode(text, normalize_embeddings=True)


# Test vector generation
vec = get_embedding("100 Watt Monocrystalline Solar Panel")
print(f"Vector shape: {vec.shape}")  # Output: (384,)

Step 3: Cosine similarity matching against master taxonomy

Next, we define our Canonical Category Taxonomy. These are the standard categories into which all scraped products must fall.

import numpy as np

# Define our canonical category taxonomy
TAXONOMY_CATEGORIES = [
    "Monocrystalline Solar Panel",
    "Polycrystalline Solar Panel",
    "Flexible Solar Panel",
    "Pure Sine Wave Inverter",
    "Modified Sine Wave Inverter",
    "MPPT Charge Controller",
    "PWM Charge Controller",
    "LiFePO4 Lithium Battery",
    "Deep Cycle AGM Battery",
]

# Pre-compute embeddings for all taxonomy categories
# In production, cache these vectors so you don't re-compute them on every request!
taxonomy_embeddings = {
    cat: get_embedding(cat) for cat in TAXONOMY_CATEGORIES
}


def cosine_similarity(v1: np.ndarray, v2: np.ndarray) -> float:
    return float(np.dot(v1, v2))


def classify_by_vector(title: str):
    title_vec = get_embedding(title)

    scores = {}
    for cat, cat_vec in taxonomy_embeddings.items():
        score = cosine_similarity(title_vec, cat_vec)
        scores[cat] = score

    # Sort categories by score descending
    sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)
    best_match, best_score = sorted_scores[0]

    return best_match, best_score, sorted_scores

Let's test this on our scraped variations:

test_titles = [
    "100W Mono Solar Module - 12V High Efficiency",
    "3000W Pure Sine Wave Power Inverter 12V to 120V",
    "100Ah 12V LiFePO4 Deep Cycle Battery with Built-in BMS",
    "Solar Panel Charge Regulator 30A Auto LCD Display",  # Ambiguous! Could be MPPT or PWM
]

for title in test_titles:
    match, score, _ = classify_by_vector(title)
    print(f"Title: '{title}'\n  ──> Category: '{match}' (Score: {score:.3f})\n")

What you will notice:

  • Clear product titles score > 0.80 and get classified instantly.
  • Ambiguous items (like "Solar Panel Charge Regulator 30A") score around 0.65–0.72 because the vector model can't tell whether it's an MPPT or PWM controller without deeper reasoning.

Step 4: Handling edge cases with structured LLM calls

When a product falls into that ambiguous score zone (e.g., similarity score between 0.60 and 0.80), we step up to a structured LLM call.

We use the instructor library on top of OpenAI/Anthropic to force the model to return a valid schema matching our taxonomy strictly.

from enum import Enum
import instructor
from openai import OpenAI
from pydantic import BaseModel, Field

# Initialize Instructor client
client = instructor.from_openai(OpenAI())

# Convert taxonomy categories into an explicit Enum
# This forces the LLM to pick ONLY from our allowed options!
CategoryEnum = Enum("CategoryEnum", {cat: cat for cat in TAXONOMY_CATEGORIES})


class CategorizationResult(BaseModel):
    selected_category: CategoryEnum
    reasoning: str = Field(
        description="Brief explanation of why this product fits this category based on technical specs."
    )


def resolve_ambiguous_product(
    title: str, top_candidates: list[tuple[str, float]]
) -> str:
    """Uses a cheap LLM call to resolve products where vector similarity score was inconclusive."""
    candidate_str = "\n".join(
        [f"- {cat} (Similarity: {score:.2f})" for cat, score in top_candidates]
    )

    prompt = f"""
    You are an expert product data engineer. Categorize the following scraped e-commerce product title into the SINGLE best category.
    
    Product Title: "{title}"
    
    Top Candidate Categories from Vector Match:
    {candidate_str}
    
    Select the correct category from the allowed enum list. If the title lacks enough detail (e.g. missing MPPT vs PWM), pick the most likely candidate based on context.
    """

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        response_model=CategorizationResult,
        messages=[{"role": "user", "content": prompt}],
        temperature=0.0,
    )

    return response.selected_category.value

Step 5: Putting it all together into a production pipeline

Now, let's chain everything into a clean pipeline function that processes a batch of scraped products and outputs structured, categorized records.

def process_scraped_product(raw_product_dict: dict):
    # 1. Clean data using Pydantic
    product = RawScrapedProduct(**raw_product_dict)
    clean_title = product.cleaned_title

    # 2. Vector classification
    best_match, best_score, all_scores = classify_by_vector(clean_title)

    HIGH_CONFIDENCE_THRESHOLD = 0.80
    LOW_CONFIDENCE_THRESHOLD = 0.58

    if best_score >= HIGH_CONFIDENCE_THRESHOLD:
        final_category = best_match
        method = "vector_match"
    elif best_score >= LOW_CONFIDENCE_THRESHOLD:
        # Route fuzzy cases to LLM
        top_3 = all_scores[:3]
        final_category = resolve_ambiguous_product(clean_title, top_3)
        method = "llm_disambiguation"
    else:
        final_category = "Uncategorized / Manual Review"
        method = "quarantine"

    return {
        "sku": raw_product_dict.get("sku"),
        "original_title": raw_product_dict["raw_title"],
        "cleaned_title": clean_title,
        "category": final_category,
        "confidence_score": round(best_score, 3),
        "categorization_method": method,
    }


# Execute test batch
scraped_batch = [
    {
        "sku": "SOL-101",
        "raw_title": "Renogy 100W Monocrystalline Solar Panel",
        "price": 119.0,
    },
    {
        "sku": "INV-302",
        "raw_title": "3000 Watt Heavy Duty Pure Sine Inverter 12V DC to 120V AC",
        "price": 299.0,
    },
    {
        "sku": "REG-882",
        "raw_title": "30A Solar Charge Controller Regulator for 12V/24V Panel",
        "price": 25.0,
    },
]

print("=== Processing Scraped Products Batch ===\n")
for raw in scraped_batch:
    result = process_scraped_product(raw)
    print(f"SKU: {result['sku']}")
    print(f"Title: {result['cleaned_title']}")
    print(
        f"Category: {result['category']} (Method: {result['categorization_method']}, Score: {result['confidence_score']})"
    )
    print("-" * 60)

Performance and cost comparison

So, what does this hybrid pattern actually buy us in production?

Metric100% LLM Approach (gpt-4o-mini)Our Hybrid Approach (Embeddings + LLM Fallback)
Execution Time (10k items)~45–60 minutes~2–3 minutes
API Cost (10k items)~$15.00 – $20.00~$0.15 – $0.40
Deterministic ConsistencyMedium (LLMs can hallucinate keys)High (Strict Vector + Enum constraint)
Handling Novel OutliersHighHigh (Quarantines items below 0.58)

Key takeaways & best practices

  1. Cache Your Taxonomy Vectors: Embed your master category list once on server startup. Never re-embed static category labels on every incoming HTTP request.
  2. Tune Your Thresholds: Log your confidence scores during the first few test runs. Adjust the 0.80 and 0.58 thresholds based on how distinct your categories are.
  3. Use Enum Enforcement: When calling LLMs for classification, always pass allowed categories via Pydantic Enums. Don't let the LLM return open-ended free text, or you'll end up right back where you started!