Skip to content

Python API

Generated from the public tlsforge exports and their runtime signatures. See the Python integration guide for examples.

Client

One browser identity: one fingerprint, one cookie jar, one exit IP.

A client serialises: the protocol underneath is one request at a time, so calls from several threads queue rather than overlap. That is not a limitation to work around — it is what one session is. Scrape in parallel with a pool of clients, one per proxy, which is also how the identities stay separate.

Close it when done, or use it as a context manager. Closing is final: a client is one identity, and once it has been given up there is no identity left to make requests with.

Parameters

profilestr | Nonedefault None
which browser to impersonate, e.g. "chrome".
proxystr | Nonedefault None
an http:// or socks5:// URL.
timeoutfloatdefault DEFAULT_TIMEOUT
per-request deadline, in seconds.
binarystr | os.PathLike[str] | Nonedefault None
path to the tls-forge binary, ahead of every other source.
insecurebooldefault False
skip certificate verification.
on_stderrCallable[[str], None] | Nonedefault None
receives the transport's stderr, a line at a time.

Raises

when there is no binary to run.
Client(
    *,
    profile: str | None = None,
    proxy: str | None = None,
    timeout: float = DEFAULT_TIMEOUT,
    binary: str | os.PathLike[str] | None = None,
    insecure: bool = False,
    cookie_file: str | os.PathLike[str] | None = None,
    cookie_set: str | None = None,
    on_stderr: Callable[[str], None] | None = None,
)
Example
1
2
3
4
5
import tlsforge

with tlsforge.Client(profile="chrome", timeout=45.0) as client:
    response = client.get("https://example.com/")
    print(response.status)
Response
200

Client.get()

GET a URL.

Client.get(
    url: str,
    *,
    headers: Mapping[str, str] | None = None,
    order: Sequence[str] | None = None,
    cookies: Iterable[str] | None = None,
    browser_context: BrowserContext | None = None,
    network_context: NetworkContext | None = None,
) -> Response
Example
1
2
3
response = client.get("https://example.com/")
print(response.status, response.url)
print(response.headers["content-type"])
Response
200 https://example.com/
('text/html; charset=utf-8',)

Client.post()

POST a body, in the browser context of the form or script that posts it: a request without one is a navigation typed into the address bar, which posts nothing, and is refused.

Client.post(
    url: str,
    body: str | bytes = '',
    *,
    headers: Mapping[str, str] | None = None,
    order: Sequence[str] | None = None,
    cookies: Iterable[str] | None = None,
    browser_context: BrowserContext | None = None,
    network_context: NetworkContext | None = None,
) -> Response
Example
1
2
3
4
5
6
7
response = client.post(
    "https://httpbin.org/post",
    '{"hello":"world"}',
    headers={"content-type": "application/json"},
    browser_context={"kind": "fetch", "initiator": "https://httpbin.org/"},
)
print(response.body)
Response
{
  "args": {},
  "headers": {
    …
    "Sec-Fetch-Dest": "empty",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Site": "same-origin",
    …
  },
  "method": "POST",
  …
  "json": {
    "hello": "world"
  }
}

Client.hello()

What the transport is: the protocol it speaks and what it can do, asked without a connection, and once. One older than the question speaks protocol 1, and can do nothing a client has to ask about.

Raises

the transport would not start, died, or spoke nonsense; asked again next time.
the deadline passed with no answer; asked again next time.
Client.hello() -> Hello
Example
1
2
3
hello = client.hello()
print(hello.protocol, hello.engine_major, hello.version)
print("browser_context" in hello.capabilities)
Response
3 1 1.0.1
True

Client.request()

Make a request.

Parameters

urlstr
methodstrdefault 'GET'
headersMapping[str, str] | Nonedefault None
the request's own fields. Without a browser context, each goes where Chrome writes that field, in place of Chrome's own, and one Chrome has no place for after user-agent, by the bytes of its name; in one, what the page's script gives fetch() or an XHR.
orderSequence[str] | Nonedefault None
the order of the headers you send, for a profile that lays them out as given. Without it they go sorted.
bodystr | bytes | Nonedefault None
cookiesIterable[str] | Nonedefault None
name=value pairs added to the jar before the request.
browser_contextBrowserContext | Nonedefault None
the browser context the request is made in, by this package's names (BrowserContext), sent only to a transport that says, when asked with hello, that it applies one.
network_contextNetworkContext | Nonedefault None

Raises

the request ran and failed — refused, DNS, TLS.
the transport would not start, died, or spoke nonsense. The client stays usable.
the deadline passed with no answer.
a browser context, to a transport that does not apply one; the request was not sent.
TypeError
a browser context that is no mapping, or has a key there is none of; nothing was asked.
Client.request(
    url: str,
    *,
    method: str = 'GET',
    headers: Mapping[str, str] | None = None,
    order: Sequence[str] | None = None,
    body: str | bytes | None = None,
    cookies: Iterable[str] | None = None,
    browser_context: BrowserContext | None = None,
    network_context: NetworkContext | None = None,
) -> Response
Example
1
2
3
4
5
6
7
8
9
response = client.request(
    "https://httpbin.org/anything",
    method="PUT",
    body='{"id": 1}',
    headers={"content-type": "application/json"},
    browser_context={"kind": "fetch", "initiator": "https://httpbin.org/"},
)
data = response.json()
print(response.status, data["method"], data["json"])
Response
200 PUT {'id': 1}

Client.close()

Stop the transport. Idempotent, and final.

At once: a request in flight, or one waiting for it, is not waited for, and raises TransportError. A write stuck on a pipe the transport has stopped reading is ended by stopping the transport first.

Client.close() -> None
Example
1
2
3
4
5
client = tlsforge.Client(profile="chrome")
try:
    response = client.get("https://example.com/")
finally:
    client.close()

BrowserContext

What in a browser a request stands for: it goes out as Chrome sends that kind, CORS and all. See GO.md, «Browser contexts».

The keys are this package's names for the daemon's fields, which the client sends as the daemon names them: referrer_policy is its referrerPolicy. A key there is none of is a TypeError.

Keys

kindLiteral['navigation', 'form', 'fetch', 'xhr']
initiatorstroptional
The URL of the page that sends it. A form, fetch() and an XHR need one; a navigation without one is typed into the address bar.
referrer_policyLiteral['no-referrer', 'no-referrer-when-downgrade', 'origin', 'origin-when-cross-origin', 'same-origin', 'strict-origin', 'strict-origin-when-cross-origin', 'unsafe-url']optional
That page's referrer policy; strict-origin-when-cross-origin when omitted.
modeLiteral['cors', 'no-cors', 'same-origin']optional
fetch()'s request mode; cors when omitted. Only for fetch().
credentialsLiteral['same-origin', 'include', 'omit']optional
fetch()'s credentials mode; same-origin when omitted. An XHR takes same-origin or include, which is withCredentials.
class BrowserContext(TypedDict)
Example
1
2
3
4
5
6
7
context: tlsforge.BrowserContext = {
    "kind": "fetch",
    "initiator": "https://example.com/",
    "mode": "cors",
    "credentials": "include",
}
response = client.get("https://example.com/", browser_context=context)

NetworkContext

Actual network metadata, with no precomputed RTT or downlink values.

Keys

typeLiteral['unknown', 'ethernet', 'wifi', '2g', '3g', '4g', '5g', 'none', 'bluetooth']
idstr
generationint
signalOptional[int]
class NetworkContext(TypedDict)
Example
1
2
3
4
5
6
7
network: tlsforge.NetworkContext = {
    "type": "wifi",
    "id": "office",
    "generation": 1,
    "signal": 4,
}
response = client.get("https://example.com/", network_context=network)

Hello

What a transport is, as it says when asked: the protocol it speaks, and what it can do that a client has to ask about before relying on it. One older than the question speaks protocol 1 and can do nothing it is asked about.

Fields

protocolint
capabilitiestuple[str, ...]
engine_majorint | Nonedefault None
versionstr | Nonedefault None
Hello(
    protocol: int,
    capabilities: tuple[str, ...],
    engine_major: int | None = None,
    version: str | None = None,
)
Example
print(client.hello())
Response
Hello(protocol=3, capabilities=('browser_context', 'engine_major', 'catalogue_json_v1', 'network_hints_estimator_v1', 'network_context_v1'), engine_major=1, version='1.0.1')

Response

What came back.

Fields

statusint
urlstr
The final URL, after redirects.
bodystr
The response as text. Bytes that are not valid UTF-8 appear as U+FFFD; use content when the response is not text.
contentbytesdefault b''
The response as bytes, exactly as they arrived. This is the one to use for images, archives, or any body that is not text.
headersMapping[str, tuple[str, ...]]default dict()
Header values in wire order. Values stay separate because folding set-cookie, among others, changes its meaning.
cookiestuple[str, ...]default ()
What the jar holds for this URL afterwards.
Response(
    status: int,
    url: str,
    body: str,
    content: bytes = b'',
    headers: Mapping[str, tuple[str, ...]] = dict(),
    cookies: tuple[str, ...] = (),
)
Example
1
2
3
response = client.get("https://example.com/")
print(response.ok, len(response.content))
print(response.cookies)
Response
True 577
()

Response.ok

Did the server answer with a 2xx?

Response.ok: bool

Response.json()

The body parsed as JSON. Raises json.JSONDecodeError if it is not.

Response.json(**kwargs: Any) -> Any
Example
data = response.json()
print(data["json"])
Response
{'hello': 'world'}

DEFAULT_TIMEOUT

DEFAULT_TIMEOUT = 45.0

MAX_REQUEST_BYTES

The most a request can be as the transport reads it: one line of JSON, its newline included, in UTF-8. A longer one would end the transport, and the session in it, so it is refused before it is sent.

MAX_REQUEST_BYTES = 16 * 1024 * 1024

TLSForgeError

Base for everything this package raises.

class TLSForgeError(Exception)

BinaryNotFound

The transport binary could not be found or does not exist.

An install problem rather than a request problem: no retry will help, and the message says which of the four places were looked in.

class BinaryNotFound(TLSForgeError)

TransportError

The transport process failed: it would not start, died, or spoke nonsense.

The request did not happen, or happened and the answer was lost. The client stays usable — the next request starts a fresh process.

class TransportError(TLSForgeError)

SessionReset

The request was not sent: the transport the client's session was in has gone, and its cookies, TLS sessions and connections went with it.

Raised for every request waiting when that happens, or for the next one made when none was waiting. Requests after that start a new session in a new transport: the client never promises the identity it had before. A TransportError, so that code catching those catches this too.

class SessionReset(TransportError)

RequestFailed

The transport ran the request and the request itself failed.

A refused connection, a DNS failure, a TLS error: the far end's doing, not the transport's. Distinct from TransportError because retrying this one can make sense and there is nothing wrong locally.

class RequestFailed(TLSForgeError)
Example
1
2
3
4
try:
    client.request("https://example.com/", method="DELETE")
except tlsforge.RequestFailed as error:
    print(error)
Response
tlsforge: DELETE https://example.com/ needs a browser context: without one it goes as a navigation typed into the address bar, a GET with no body; say the form, fetch() or XHR that sends it, and from which page

Timeout

The deadline passed with no answer.

Also a builtin TimeoutError, so code that already catches those catches this without knowing about this package.

class Timeout(TLSForgeError, TimeoutError)

Unsupported

The transport cannot make the request as asked, and it was not sent.

It does not do what the request needs, as it says when asked with Client.hello(), or it is older than the question. A newer tls-forge, or a request that does not need it, is the fix.

class Unsupported(TLSForgeError)

resolve_binary()

Find the transport binary.

Parameters

explicitstr | os.PathLike[str] | Nonedefault None
a path to use as given, ahead of everything else.

Raises

when nothing was found, or when a path that was named does not exist.
resolve_binary(explicit: str | os.PathLike[str] | None = None) -> str
Example
print(tlsforge.resolve_binary())
Response
…/lib/python3.11/site-packages/tlsforge/bin/tls-forge

bundled_binary()

The binary shipped inside this package, whether or not it is there.

bundled_binary(platform: str = sys.platform) -> Path

exe_name()

The executable's name, which is the command's name, not the package's.

exe_name(platform: str = sys.platform) -> str

ENV_VAR

The environment variable that overrides every other source.

ENV_VAR = 'TLSFORGE_BIN'