How Do You Generate a Browser Fingerprint in Python?
The short answer: a browser fingerprint generator python setup does one of two jobs. It either produces synthetic screen, navigator and header values from real-world distributions — BrowserForge does that in roughly 0.1–0.2 milliseconds per call — or it collects real signals inside a browser and resolves them to a visitor ID through a commercial service. Most teams need both: generated fixtures for tests, real collection for analytics.

📌 TL;DR Executive Summary
- Core Takeaway: Python generates fingerprints, it does not read them. BrowserForge produces realistic screen, navigator, header, font and codec objects; Fingerprint’s server SDK resolves real browser signals into a visitor ID.
- Key Risk/Challenge: Generated values are data, not a browser. Canvas hashes, WebGL render output and audio hashes are computed by the browser engine and cannot be produced from a Python script.
- Recommended Solution: Store one generated fingerprint per test profile, dump it to JSON, reuse it for the whole run, and keep the Fingerprint secret key server-side only.
What a Browser Fingerprint Is Made Of
A fingerprint is a bundle of values a browser exposes without asking permission. Screen geometry, installed fonts, timezone, language list, CPU core count, GPU strings, canvas rendering output and audio processing quirks all contribute a little entropy each. Fingerprint, the commercial device-intelligence vendor, says its visitor ID is derived from more than 100 browser and hardware signals and does not rely on cookies or IP addresses.
| Signal group | Typical values | Available from Python? | Where the real value comes from |
|---|---|---|---|
| Screen and viewport | width, height, colour depth, pixel ratio | Yes, generated | window.screen |
| Navigator | user agent, platform, languages, hardware concurrency | Yes, generated | navigator |
| HTTP headers | User-Agent, Accept-Language, Sec-CH-UA | Yes, generated | The request itself |
| Fonts, plugins, codecs | font list, PDF viewer, audio/video codec support | Yes, as data lists | document.fonts, navigator.plugins |
| Graphics hardware | GPU vendor and renderer string | Yes, as a string | WebGL debug renderer info |
| Canvas and audio | rendering hash, AudioContext hash | No | Pixel output, offline audio buffer |
| Network context | timezone, locale, geolocation | Only as constraints | Intl API plus the exit IP |
That middle column is the whole problem. Python can describe a plausible Windows desktop with a 1920×1080 screen and an English locale. It cannot make a browser compute the same canvas hash that machine would produce. If you want a deeper walkthrough of each field and how much identifying power it carries, read what a browser fingerprint contains before you write any code.
Prerequisites: What You Need Before Step 1
- Python 3.10 or newer — the FastAPI stack in step 6 uses modern typing syntax.
- pip and a virtual environment — install into a
venv, not the system interpreter. - BrowserForge — open-source header and fingerprint generator, current release 1.2.4.
- FastAPI and uvicorn — only needed for the HTTP service in step 6 and the final script.
- A Fingerprint account — free tier, with a Public API key for the browser agent and a Server API key for your backend. Optional if you only need generated fixtures.
- A test target you own — your own staging site, a lab page, or a unit-test suite. Not a third-party site.
Step 1 — Install the Libraries
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install "browserforge==1.2.4" "fastapi" "uvicorn[standard]" "fingerprint-server-sdk>=9,<10" python-dotenv
Pin BrowserForge if you care about reproducible fixtures — its output distributions have changed between releases, and an unpinned install will quietly rename keys in your saved JSON. The Fingerprint SDK is on the 9.x line; keep the major version pinned so method signatures stay stable.
Create a .env file next to your code and add both keys there. Never hardcode them:
FINGERPRINT_PUBLIC_KEY=your_public_key
FINGERPRINT_SECRET_KEY=your_secret_key
Step 2 — Generate a Fingerprint Object With BrowserForge
For the generation half, the browser fingerprint generator python ecosystem has one obvious starting point: BrowserForge, a Python reimplementation of Apify’s fingerprint-suite. Instead of picking random values per field, it samples browser, OS and device combinations using real-world frequency distributions, then fills in the dependent fields so the object stays internally consistent.
from browserforge.fingerprints import FingerprintGenerator, Screen
generator = FingerprintGenerator(
browser="chrome",
os="windows",
device="desktop",
locale=("en-US", "en"),
screen=Screen(min_width=1280, max_width=1920, min_height=720, max_height=1080),
)
fingerprint = generator.generate()
print(type(fingerprint).__name__) # Fingerprint
print(fingerprint.screen.width, fingerprint.screen.height)
print(fingerprint.navigator.userAgent)
print(fingerprint.headers["User-Agent"])
The returned Fingerprint object carries screen, navigator, headers, videoCodecs, audioCodecs, pluginsData, battery, videoCard, multimediaDevices and fonts. Because the header set is generated alongside the navigator, the user agent in headers matches the one in navigator — that consistency is the point of using the object rather than generating each piece separately.
The generator also accepts mock_webrtc and slim switches, plus the same keyword arguments HeaderGenerator takes. Those two switches change what the returned object contains; leave them out of fixtures until you know which fields your assertions read, because a reduced object will fail the key check in step 4. None of these options makes the output match a real browser’s canvas or WebGL values.
Note what you did not get: no canvas hash, no WebGL render output, no audio fingerprint. The videoCard field gives you a GPU renderer string as text; it does not reproduce the pixels a real GPU would draw. If you need to reason about that gap, our canvas fingerprinting breakdown explains what the browser hashes and why a string substitution will not match it.
strict=True on the generator while writing tests. With the default, contradictory constraints get loosened silently and you end up asserting against a fingerprint that ignores half your parameters. Strict mode raises instead, which is what you want in CI. Full option reference lives on the BrowserForge package page.
Step 3 — Generate Headers That Match the Fingerprint
HeaderGenerator is the standalone half of the package. Use it when you only need a request header set and do not care about the rest of the object.
from browserforge.headers import HeaderGenerator
header_generator = HeaderGenerator(
browser="chrome",
os="windows",
device="desktop",
locale=("en-US", "en"),
http_version="2",
)
headers = header_generator.generate()
for name, value in headers.items():
print(f"{name}: {value}")
Here is the trap. If you call HeaderGenerator() and FingerprintGenerator() separately, you get two independent samples: the user agent in the headers can name a different Chrome major version than the platform string in the navigator. Any code that compares them — including your own assertions — will flag the mismatch. Either generate the fingerprint once and read fingerprint.headers, or pass the same explicit constraints to both calls.
Step 4 — Dump the Fingerprint to JSON and Check It
The Fingerprint dataclass serialises with .dumps(). Round-trip it through json so the saved fixture is plain data your test runner can diff. That saved record is the most useful output a browser fingerprint generator python run can give you.
import json
from pathlib import Path
REQUIRED_KEYS = {"screen", "navigator", "headers", "fonts"}
def save_fixture(fingerprint, path: Path) -> dict:
record = json.loads(fingerprint.dumps())
missing = REQUIRED_KEYS - record.keys()
if missing:
raise ValueError(f"fingerprint missing keys: {sorted(missing)}")
path.write_text(json.dumps(record, indent=2), encoding="utf-8")
return record
record = save_fixture(fingerprint, Path("fixtures/chrome-win-desktop.json"))
print(record["navigator"]["userAgent"])
The explicit key check is not paranoia. When BrowserForge changes its model between minor versions, a renamed field fails loudly here instead of producing a KeyError three layers deep in your test suite.
Step 5 — Keep One Fingerprint Stable Across a Session
Regenerating per request is the most common bug in this space. A browser fingerprint generator python call belongs once per profile, not once per HTTP request. A session that reports a different screen size on the first and third request is internally inconsistent, and your own instrumentation will record it as two separate visitors. Generate once, keyed by profile, and reuse.
import json
import pathlib
from browserforge.fingerprints import FingerprintGenerator
STORE_PATH = pathlib.Path("fingerprints.json")
_generator = FingerprintGenerator(browser="chrome", device="desktop")
def _read_store() -> dict:
if STORE_PATH.exists():
return json.loads(STORE_PATH.read_text(encoding="utf-8"))
return {}
def get_fingerprint(profile_id: str) -> dict:
store = _read_store()
if profile_id in store:
return store[profile_id]
record = json.loads(_generator.generate().dumps())
store[profile_id] = record
STORE_PATH.write_text(json.dumps(store, indent=2), encoding="utf-8")
return record
Two things to fix before this goes anywhere near production. First, write_text is not atomic — two workers can clobber the file. Write to a temp file and os.replace it, or move the store to SQLite. Second, tie the locale and timezone constraints to the region you are simulating, because a US-English navigator reporting a Kyiv timezone is exactly the kind of internal contradiction the exercise is meant to surface. Our guide to timezone fingerprinting covers how that field is read and why it must line up with the rest of the profile.
Step 6 — Add a Server-Side Visitor ID With Fingerprint
Generated values only describe a browser. To identify a real one, the documented pattern is: collect signals in the browser, receive only an event_id on your server, then fetch the full record server-to-server so the client cannot tamper with the result.
// Browser side: load the agent with your PUBLIC key, then send only the event ID.
const fpPromise = import("https://fpjscdn.net/v3/YOUR_PUBLIC_API_KEY")
.then((FingerprintJS) => FingerprintJS.load());
fpPromise
.then((fp) => fp.get())
.then((result) =>
fetch("/identify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ event_id: result.event_id }),
})
);
import os
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from fingerprint_server_sdk import FingerprintApi
from fingerprint_server_sdk.configuration import Configuration
configuration = Configuration(api_key=os.environ["FINGERPRINT_SECRET_KEY"])
fingerprint_client = FingerprintApi(configuration)
app = FastAPI()
class IdentifyRequest(BaseModel):
event_id: str
@app.post("/identify")
def identify(payload: IdentifyRequest) -> dict:
try:
event = fingerprint_client.get_event(payload.event_id)
except Exception as exc:
raise HTTPException(status_code=502, detail="Fingerprint lookup failed") from exc
products = event.products
if products is None or products.identification is None:
raise HTTPException(status_code=422, detail="No identification result")
return {"visitor_id": products.identification.data.visitor_id}
Treat the event ID as single-use: resolve it immediately after collection and do not store it for later replay. Pin the SDK to 9.x, since the response object is nested and method names have moved between majors. Fingerprint’s own Python integration walkthrough tracks the current signatures if yours drift.
python-dotenv or your platform’s secret store, and make sure it stays out of logs and error traces — a stack trace that prints the configuration object leaks the key.
When Generating Fingerprints Is Appropriate
Testing your own site
Generating fixtures is straightforwardly useful when the target is yours. You can assert that your analytics tags fire for a given screen size, that your consent banner renders before collection starts, and that your own detection rules catch the combinations you expect. No third party is involved and nothing leaves your environment.
Analytics on real visitors needs a lawful basis
Collecting signals from other people is a different activity with its own rules. Under GDPR, fingerprinting that identifies a device is personal data processing, and fines for non-compliant processing reach up to €20 million. Check whether your jurisdiction requires consent, and disclose the practice in your privacy notice rather than burying it.
What a generator never does
It does not change what a real browser reports, and it does not give you standing to operate accounts a platform has restricted. If an account is suspended, the route back is the platform’s own appeal or verification process. If you need several accounts on one platform, follow that platform’s published process — Amazon’s approval for an additional seller account, Meta Business Manager roles for agency work — rather than looking for a way around the limit.
The legitimate version of “several separate identities in real browser sessions” is a browser profile manager, not a Python script. Send.win runs isolated profiles that each keep their own cookies, storage, session, fingerprint settings and proxy, with the fingerprint handled inside the Chromium-based engine rather than assembled from header strings in your own code.
Which Library Fits Which Job
Decide which half of the browser fingerprint generator python job you actually need before you compare options — synthetic fixtures for your own tests, or real collection from browsers in production.
| Option | What it returns | Cost and speed | Use it when |
|---|---|---|---|
| BrowserForge | Screen, navigator, headers, fonts, codecs, media devices as Python objects | Open source; 0.1–0.2 ms per generation | You need deterministic test fixtures or header sets |
Crawlee BrowserforgeFingerprintGenerator |
Fingerprint wrapper that keeps headers in sync; generation is flagged experimental | Open source, in-process | You already build on Crawlee and want its options surface |
| Fingerprint server SDK 9.x | A visitor ID from 100+ browser and hardware signals | Free tier: 1,000 web/iOS calls a month (500,000 Android); Pro Plus $99/mo for 20,000 identifications, $4 per extra 1,000 | You need to recognise returning visitors without cookies |
| FingerprintJS (open source) | A hash computed in the browser from exposed attributes | Free, self-hosted | You want a rough client-side signal and nothing more |
Keep FingerprintJS and Fingerprint’s commercial product separate in your head. The open-source library is a small browser script with no server-side record behind it; the paid product is a service with a maintained signal set and a stability guarantee. Teams routinely conflate the two in architecture reviews and then discover the free library returns a different value on the next browser build.
Common Errors and How to Fix Them
ModuleNotFoundError: No module named ‘browserforge’
Almost always a virtual environment mismatch. Check which python against the interpreter your editor uses, and confirm the wheel installed for your platform — BrowserForge ships prebuilt wheels through version 1.2.4, so a source build usually means the interpreter version is unsupported.
Strict mode raises instead of returning a fingerprint
Your constraints contradict each other. Asking for os="windows" with a locale that never appears on Windows, or a screen range narrower than any real device, leaves the generator with nothing to sample. Widen the range or drop one constraint and retry.
The user agent in headers does not match the navigator
Two independent generations, as covered in step 3. Read fingerprint.headers from the same object, or pass identical constraints to both generators.
The visitor ID lookup returns 401, 403 or 404
Three usual causes: the Server API key was used where the Public key belongs (or the reverse), the key pair belongs to a different workspace, or the event ID was already redeemed or has expired. Resolve the ID immediately after collection and check you are not reusing one from an earlier request.
Values change between test runs
A browser fingerprint generator python library samples from a distribution by design, and BrowserForge documents no seed parameter for reproducing output. Do not try to derive a fingerprint from a seed — persist the generated record as in step 5 and load it back.
Generated values do not match what the browser actually reports
This is expected and worth asserting on. Load your lab page with the generated object applied, read the browser’s real values, and diff. If canvas or WebGL hashes appear in your comparison, they will never align with generated data because the browser computes them from rendering. Cross-check against a known set of fingerprint test tools before you blame the generator.
The Full Final Script
This service does both jobs: it serves a stable generated fixture per profile, and it resolves real event IDs server-side. Save it as fingerprint_service.py and run uvicorn fingerprint_service:app --reload.
"""Local fingerprint fixture service.
Serves a stable BrowserForge fingerprint per profile ID and resolves
Fingerprint event IDs to visitor IDs server-side. For testing sites you own.
"""
import json
import os
import pathlib
from browserforge.fingerprints import FingerprintGenerator
from fastapi import FastAPI, HTTPException
from fingerprint_server_sdk import FingerprintApi
from fingerprint_server_sdk.configuration import Configuration
from pydantic import BaseModel
STORE_PATH = pathlib.Path("fingerprints.json")
GENERATOR = FingerprintGenerator(browser="chrome", device="desktop")
configuration = Configuration(api_key=os.environ["FINGERPRINT_SECRET_KEY"])
fingerprint_client = FingerprintApi(configuration)
app = FastAPI(title="Fingerprint fixtures")
def read_store() -> dict:
if STORE_PATH.exists():
return json.loads(STORE_PATH.read_text(encoding="utf-8"))
return {}
def write_store(store: dict) -> None:
tmp = STORE_PATH.with_suffix(".tmp")
tmp.write_text(json.dumps(store, indent=2), encoding="utf-8")
os.replace(tmp, STORE_PATH)
@app.get("/fingerprint/{profile_id}")
def get_fingerprint(profile_id: str) -> dict:
store = read_store()
if profile_id not in store:
store[profile_id] = json.loads(GENERATOR.generate().dumps())
write_store(store)
return store[profile_id]
@app.delete("/fingerprint/{profile_id}")
def reset_fingerprint(profile_id: str) -> dict:
store = read_store()
store.pop(profile_id, None)
write_store(store)
return {"reset": profile_id}
class IdentifyRequest(BaseModel):
event_id: str
@app.post("/identify")
def identify(payload: IdentifyRequest) -> dict:
try:
event = fingerprint_client.get_event(payload.event_id)
except Exception as exc:
raise HTTPException(status_code=502, detail="Fingerprint lookup failed") from exc
products = event.products
if products is None or products.identification is None:
raise HTTPException(status_code=422, detail="No identification result")
return {"visitor_id": products.identification.data.visitor_id}
Test it with two calls to /fingerprint/test-a. The payload should be identical both times; call DELETE and it regenerates. Point your staging suite at the service, assert on the fields you care about, and leave real collection to the browser-side agent.
🏆 Send.win Verdict
The code in this guide generates fingerprint data for tests — it does not create a real browsing identity. When you need actual isolated sessions, Send.win takes the different route: each profile keeps its own cookies, storage, session, proxy and a consistent fingerprint handled inside the Chromium-based engine, on Windows, macOS and Linux, or in the cloud browser running from Helsinki. It has no API, SDK or headless mode, so it complements a Python test harness rather than plugging into one.
See Send.win plans — paid plans start at $19/mo with a 7-day money-back guarantee on your first card purchase, and the free cloud demo needs no install.
Frequently Asked Questions
Can Python generate a browser fingerprint?
Yes, but only as data. Libraries such as BrowserForge produce a structured object with screen, navigator, header, font and codec values sampled from real-world distributions. Python cannot compute the canvas, WebGL or audio hashes a browser derives from rendering, so a generated object describes a device rather than reproducing one.
Which library generates browser headers and fingerprints?
BrowserForge covers both: FingerprintGenerator returns a full object including matching headers, and HeaderGenerator returns headers alone. Crawlee for Python wraps the same library as BrowserforgeFingerprintGenerator, though that wrapper is marked experimental and its return type is expected to change.
How do I dump a BrowserForge fingerprint as JSON?
Call .dumps() on the returned Fingerprint object, then pass the string through json.loads so you hold a plain dictionary. Write that dictionary to a file with indent=2 and commit it, and your fixtures stop changing between test runs.
How accurate is a generated fingerprint?
Accurate in the sense that the field combinations are plausible and internally consistent, which is what test fixtures need. It is not a measurement of any real device. Treat generated values as synthetic input for your own assertions, not as a report on what a given browser would expose.
How do I keep a fingerprint consistent across sessions?
Generate once per profile ID, store the JSON, and load it on every subsequent request rather than regenerating. BrowserForge samples randomly within its constraints and documents no seed for reproducing output, so persistence is the reliable way to keep a session’s values stable.
Is BrowserForge the same as Apify’s fingerprint-suite?
No. It is a Python reimplementation that mimics the original’s approach of sampling from real-world browser, OS and device frequency distributions. The API surface differs, so code written against fingerprint-suite needs adjusting rather than copying.
Do I need a paid service to get a visitor ID?
Not for generated fixtures — BrowserForge is open source and free. You do need a collection service if you want a stable identifier from real browsers without cookies. Fingerprint’s free tier covers 1,000 web and iOS calls a month plus 500,000 Android calls, which is enough to evaluate the flow.
What does Fingerprint’s free tier include?
As listed on its pricing page, the free plan covers 1,000 web and iOS identifications per month and 500,000 Android calls, and starts with a 14-day trial of Pro Plus. Pro Plus begins at $99 per month for 20,000 web or iOS identifications, with $4 per additional 1,000, and only successful identifications that return an event ID are billed.
How Send.win Helps With Browser Fingerprint Generator Python
Send.win is a browser profile manager for professionals and teams: every account gets its own isolated browser profile.
- Isolated profiles – separate cookies, storage and sessions per profile
- Fingerprint protection – each profile keeps its own consistent browser fingerprint, so profiles never share one browser identity
- Desktop app + cloud browser – native app for Windows, macOS and Linux, or run profiles in the cloud with no install
- Residential proxies included – on Pro and Team, with timezone and locale matched to the proxy
- Team sharing – share a signed-in profile with a teammate without sharing the password
Try the free cloud demo — no install — or download the desktop app. Paid plans start at $19/month, and your first card purchase is covered by a 7-day money-back guarantee (see pricing).