{"id":28745,"date":"2026-11-29T08:46:30","date_gmt":"2026-11-29T08:46:30","guid":{"rendered":"https:\/\/capskip.com\/?p=28745"},"modified":"2026-11-29T08:46:30","modified_gmt":"2026-11-29T08:46:30","slug":"http2-fingerprint-python","status":"publish","type":"post","link":"https:\/\/capskip.com\/zh\/http2-fingerprint-python\/","title":{"rendered":"Python \u4e2d\u7684 HTTP2 \u6307\u7eb9\uff1a\u6bcf\u4e2a\u5ba2\u6237\u7aef\u5230\u5e95\u53d1\u9001\u4ec0\u4e48"},"content":{"rendered":"<p>To read your http2 fingerprint in Python, record the first frames a client sends on a connection you control and write them in the format Akamai proposed: the SETTINGS values in the order sent, the WINDOW_UPDATE increment, any PRIORITY frames and the order of the pseudo-headers. On Windows 11, httpx with HTTP\/2 on sent a string unlike the Chrome string, curl_cffi sent the Chrome string exactly, and requests sent no HTTP\/2 at all. Below are the recorder, the measurements, what a Python option can change, and where CapSkip enters: it solves the CAPTCHA you are served once your client gets through, and it never changes a frame.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">What you need<\/h2>\n<ul>\n<li>Python 3.10 or later: capskip 1.8.0, h2 4.4.1, hpack 4.2.0, requests 2.34.2 and curl_cffi 0.17.0 all declare 3.10 in python_requires, while httpx 0.28.1 declares 3.8 and cryptography 50.0.2 declares 3.9. I ran every Python block on 3.11.7, 3.13.7 and 3.14.0 and none on 3.10.<\/li>\n<li>One virtual environment that holds the packages below.<\/li>\n<li>Chrome on the machine that runs the listener, for the browser measurement. My copy was 157.0.8103.78, started in the new headless mode.<\/li>\n<li>CapSkip 5.7.0 for the last step only, running on a Windows PC as the setup guide describes. Every CapSkip result below comes from a mock of in.php and res.php that I wrote on its own port. I sent no task to the real app and none to a real site.<\/li>\n<li>An address for CapSkip. Local mode keeps it on the loopback address, which only that PC can reach. Server mode listens on a network address so other machines can call the API, as the <a href=\"https:\/\/capskip.com\/setup-guide\/#connection-settings\">connection settings<\/a> section of the setup guide explains.<\/li>\n<\/ul>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># In PowerShell, in a new empty folder\npython -m venv .venv\n.\\.venv\\Scripts\\Activate.ps1\npython -m pip install capskip &quot;httpx[http2]&quot; curl_cffi requests cryptography<\/pre>\n<\/div>\n<p>The allow and block rules in this guide are mine, written as stand-ins for whatever a real site might do. Nothing here says that a real vendor blocks on any value shown. The TLS handshake that comes before these frames is a separate layer, and the <a href=\"https:\/\/capskip.com\/tls-fingerprinting-python\/\">TLS fingerprinting in Python<\/a> guide owns it.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 1: record the first frames before any HTTP code runs<\/h2>\n<p>An HTTP library parses the frames and keeps them from you, so read the bytes first. The string has four parts joined by a pipe. The first lists the SETTINGS as id:value pairs in sent order, the second is the WINDOW_UPDATE increment, the third lists PRIORITY frames as stream:exclusive:depends-on:weight, and the fourth gives the first letters of the pseudo-headers in sent order. I followed the <a href=\"https:\/\/www.blackhat.com\/docs\/eu-17\/materials\/eu-17-Shuster-Passive-Fingerprinting-Of-HTTP2-Clients-wp.pdf\" rel=\"noopener nofollow\" target=\"_blank\">Akamai white paper<\/a>, which defines the first three parts and adds the fourth. The paper writes 00 for a missing WINDOW_UPDATE, and so do I.<\/p>\n<p>Save this block as fp.py.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># fp.py: read the first HTTP\/2 frames of a connection and build an Akamai-style fingerprint.\nfrom hpack import Decoder\n\nPREFACE = b&quot;PRI * HTTP\/2.0\\r\\n\\r\\nSM\\r\\n\\r\\n&quot;\n\n\nclass Frames:\n    &quot;&quot;&quot;Feed it the raw bytes a client sends. It records and never answers.&quot;&quot;&quot;\n\n    def __init__(self):\n        self.buf, self.ok = b&quot;&quot;, None  # ok: did the 24 byte preface arrive?\n        self.settings, self.update, self.priority = None, None, []\n        self.names = None  # header names of the first request, in wire order\n        self.block, self.decoder = b&quot;&quot;, Decoder()\n\n    def feed(self, data):\n        self.buf += data\n        if self.ok is None and len(self.buf) &gt;= 24:\n            self.ok = self.buf.startswith(PREFACE)\n            self.buf = self.buf[24:]\n        while self.ok and len(self.buf) &gt;= 9:\n            size, kind, flags = int.from_bytes(self.buf[:3], &quot;big&quot;), self.buf[3], self.buf[4]\n            stream = int.from_bytes(self.buf[5:9], &quot;big&quot;) &amp; 0x7FFFFFFF\n            if len(self.buf) &lt; 9 + size:\n                return\n            body, self.buf = self.buf[9 : 9 + size], self.buf[9 + size :]\n            self.frame(kind, flags, stream, body)\n\n    def frame(self, kind, flags, stream, body):\n        if self.names is not None:\n            return  # only the frames before the first request count\n        if kind == 4 and not flags &amp; 1 and self.settings is None:  # SETTINGS, not an ack\n            self.settings = [(int.from_bytes(body[i : i + 2], &quot;big&quot;), int.from_bytes(body[i + 2 : i + 6], &quot;big&quot;)) for i in range(0, len(body), 6)]\n        elif kind == 8 and stream == 0 and self.update is None:  # WINDOW_UPDATE on the connection\n            self.update = int.from_bytes(body[:4], &quot;big&quot;) &amp; 0x7FFFFFFF\n        elif kind == 2:  # PRIORITY: stream, exclusive bit, depends on, weight (the wire byte plus one)\n            dep = int.from_bytes(body[:4], &quot;big&quot;)\n            self.priority.append((stream, dep &gt;&gt; 31, dep &amp; 0x7FFFFFFF, body[4] + 1))\n        elif kind == 1 or kind == 9:  # HEADERS, then CONTINUATION\n            if kind == 1:\n                if flags &amp; 8:\n                    body = body[1 : len(body) - body[0]]  # padding\n                if flags &amp; 0x20:  # a priority carried inside HEADERS is not part of the string\n                    body = body[5:]\n            self.block += body\n            if flags &amp; 4:  # END_HEADERS\n                self.names = [n.decode(&quot;latin-1&quot;) for n, _ in self.decoder.decode(self.block, raw=True)]\n\n    def akamai(self):\n        s = &quot;;&quot;.join(&quot;%d:%d&quot; % kv for kv in self.settings or [])\n        wu = &quot;00&quot; if self.update is None else str(self.update)  # the paper writes 00 for no frame\n        p = &quot;,&quot;.join(&quot;%d:%d:%d:%d&quot; % t for t in self.priority) or &quot;0&quot;\n        ps = &quot;,&quot;.join(n[1] for n in self.names or [] if n.startswith(&quot;:&quot;))\n        return &quot;|&quot;.join([s, wu, p, ps])<\/pre>\n<\/div>\n<p>I checked it against the paper. Replaying the frame sequences it documents (Firefox 53 on Mac and on Android, Chrome 58, Edge 14, OkHttp 3.6, a Go client, curl 7.54 and nghttp2 1.22) in 7-byte chunks reproduced all eight printed strings. That proves the code follows the paper, not that current clients still send those frames, which the measurements are for.<\/p>\n<p>The listener is three blocks for site.py, in order. Its rule lets in only a connection whose frames match the Chrome string measured in step 2, and the path \/fp echoes what any client sent.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># site.py (part 1 of 3): imports, the mock rule and the mock pages.\nimport datetime, ipaddress, json, os, pathlib, socket, ssl, threading\nimport h2.config, h2.connection, h2.events, h2.exceptions\nfrom cryptography import x509\nfrom cryptography.hazmat.primitives import hashes, serialization\nfrom cryptography.hazmat.primitives.asymmetric import ec\nfrom cryptography.x509.oid import NameOID\nfrom fp import Frames\n\nPORT = 12860\n# The mock rule: only a connection whose first frames match this string gets the page.\nALLOW = {&quot;1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p&quot;}\nPAGE = '&lt;form method=&quot;post&quot; action=&quot;\/login&quot;&gt;&lt;input name=&quot;email&quot;&gt;&lt;div class=&quot;g-recaptcha&quot; data-sitekey=&quot;6LeMOCKMOCKMOCKMOCKMOCKMOCKMOCKMOCKMOCK0&quot;&gt;&lt;\/div&gt;&lt;\/form&gt;'\nspent = set()  # tokens this site has already accepted\n\n\ndef make_cert():\n    key = ec.generate_private_key(ec.SECP256R1())\n    name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, &quot;localhost&quot;)])\n    now = datetime.datetime.now(datetime.timezone.utc)\n    cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())\n            .serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(minutes=5))\n            .not_valid_after(now + datetime.timedelta(days=30))\n            .add_extension(x509.SubjectAlternativeName([x509.DNSName(&quot;localhost&quot;), x509.IPAddress(ipaddress.ip_address(&quot;127.0.0.1&quot;))]), False)\n            .add_extension(x509.BasicConstraints(ca=True, path_length=None), True)\n            .add_extension(x509.KeyUsage(True, False, False, False, False, True, True, False, False), True)\n            .sign(key, hashes.SHA256()))\n    pathlib.Path(&quot;cert.pem&quot;).write_bytes(cert.public_bytes(serialization.Encoding.PEM))\n    pathlib.Path(&quot;key.pem&quot;).write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))\n\n\ndef answer(method, path, headers, body, fp, names):\n    &quot;&quot;&quot;Return (status, content type, text). The rule runs first, except on \/fp, which only echoes.&quot;&quot;&quot;\n    verdict = &quot;ALLOWED&quot; if fp in ALLOW else &quot;BLOCKED&quot;\n    print(verdict, method, path, &quot;|&quot;, fp, &quot;|&quot;, &quot; &quot;.join(names), flush=True)\n    if path == &quot;\/fp&quot;:\n        return 200, &quot;application\/json&quot;, json.dumps({&quot;fp&quot;: fp, &quot;names&quot;: names})\n    if verdict == &quot;BLOCKED&quot;:\n        return 403, &quot;text\/plain&quot;, &quot;&quot;\n    if method == &quot;GET&quot; and path == &quot;\/signup&quot;:\n        return 200, &quot;text\/html&quot;, PAGE\n    if method == &quot;POST&quot; and path == &quot;\/login&quot;:\n        if not headers.get(&quot;referer&quot;, &quot;&quot;).startswith(&quot;https:\/\/127.0.0.1:%d\/&quot; % PORT):\n            return 403, &quot;text\/plain&quot;, &quot;no referer&quot;\n        token = dict(p.split(&quot;=&quot;, 1) for p in body.split(&quot;&amp;&quot;) if &quot;=&quot; in p).get(&quot;g-recaptcha-response&quot;, &quot;&quot;)\n        if token and token not in spent:\n            spent.add(token)\n            return 200, &quot;text\/html&quot;, &quot;&lt;p&gt;saved&lt;\/p&gt;&quot;\n        return 200, &quot;text\/html&quot;, &quot;&lt;p&gt;captcha check failed&lt;\/p&gt;&quot;\n    return 404, &quot;text\/plain&quot;, &quot;&quot;<\/pre>\n<\/div>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># site.py (part 2 of 3, same file): serve one connection over HTTP\/2, or over HTTP\/1.1 when the client asks for it.\ndef serve_h2(tls):\n    frames = Frames()\n    conn = h2.connection.H2Connection(h2.config.H2Configuration(client_side=False, header_encoding=&quot;utf-8&quot;))\n    conn.initiate_connection()\n    tls.sendall(conn.data_to_send())\n    reqs = {}\n    while True:\n        data = tls.recv(65535)\n        if not data:\n            return\n        frames.feed(data)  # record first, then let the h2 package see the same bytes\n        for ev in conn.receive_data(data):\n            if isinstance(ev, h2.events.RequestReceived):\n                reqs[ev.stream_id] = [dict(ev.headers), b&quot;&quot;, [n for n, _ in ev.headers]]\n            elif isinstance(ev, h2.events.DataReceived):\n                reqs[ev.stream_id][1] += ev.data\n                conn.acknowledge_received_data(ev.flow_controlled_length, ev.stream_id)\n            elif isinstance(ev, h2.events.StreamEnded):\n                headers, body, names = reqs[ev.stream_id]\n                if ev.stream_id == 1:\n                    names = frames.names  # the first request, straight from the wire\n                status, ctype, text = answer(headers[&quot;:method&quot;], headers[&quot;:path&quot;], headers, body.decode(), frames.akamai(), names)\n                raw = text.encode()\n                conn.send_headers(ev.stream_id, [(&quot;:status&quot;, str(status)), (&quot;content-type&quot;, ctype), (&quot;content-length&quot;, str(len(raw)))])\n                conn.send_data(ev.stream_id, raw, end_stream=True)\n        tls.sendall(conn.data_to_send())\n\n\ndef serve_h1(tls):\n    buf = b&quot;&quot;\n    while b&quot;\\r\\n\\r\\n&quot; not in buf:\n        chunk = tls.recv(65535)\n        if not chunk:\n            return\n        buf += chunk\n    head, _, rest = buf.partition(b&quot;\\r\\n\\r\\n&quot;)\n    lines = head.decode(&quot;latin-1&quot;).split(&quot;\\r\\n&quot;)\n    method, path, _ = lines[0].split(&quot; &quot;, 2)\n    pairs = [l.split(&quot;:&quot;, 1) for l in lines[1:]]\n    headers = {k.strip().lower(): v.strip() for k, v in pairs}\n    while len(rest) &lt; int(headers.get(&quot;content-length&quot;, 0)):\n        rest += tls.recv(65535)\n    status, ctype, text = answer(method, path, headers, rest.decode(), &quot;http\/1.1&quot;, [k.strip().lower() for k, _ in pairs])\n    raw = text.encode()\n    tls.sendall((&quot;HTTP\/1.1 %d X\\r\\ncontent-type: %s\\r\\ncontent-length: %d\\r\\nconnection: close\\r\\n\\r\\n&quot; % (status, ctype, len(raw))).encode() + raw)<\/pre>\n<\/div>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># site.py (part 3 of 3, same file): accept connections and start the listener.\ndef handle(sock):\n    tls = None\n    try:\n        tls = CTX.wrap_socket(sock, server_side=True)\n        (serve_h2 if tls.selected_alpn_protocol() == &quot;h2&quot; else serve_h1)(tls)\n    except (OSError, ssl.SSLError, h2.exceptions.ProtocolError):\n        pass\n    finally:\n        (tls or sock).close()\n\n\nif __name__ == &quot;__main__&quot;:\n    if not os.path.exists(&quot;cert.pem&quot;):\n        make_cert()\n    CTX = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)\n    CTX.load_cert_chain(&quot;cert.pem&quot;, &quot;key.pem&quot;)\n    CTX.set_alpn_protocols([&quot;h2&quot;, &quot;http\/1.1&quot;])\n    server = socket.create_server((&quot;127.0.0.1&quot;, PORT))\n    print(&quot;listening on&quot;, PORT, flush=True)\n    while True:\n        threading.Thread(target=handle, args=(server.accept()[0],), daemon=True).start()<\/pre>\n<\/div>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 2: send the same request with each client<\/h2>\n<p>Start the listener with python site.py in one window. Save the next block as clients.py and run it in a second one. Each client makes ten new connections, so a changing fingerprint would show as more than one distinct string.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># clients.py: ten new connections per client to the mock site, then print what it recorded.\nimport ssl\n\nimport httpx\nimport requests\nfrom curl_cffi import requests as curl\n\nURL = &quot;https:\/\/127.0.0.1:12860\/fp&quot;\nCA = &quot;cert.pem&quot;  # the certificate site.py wrote\nCTX = ssl.create_default_context(cafile=CA)  # httpx 0.28.1 warns about verify given as a path\n\n\ndef httpx_h2():\n    with httpx.Client(http2=True, verify=CTX) as c:  # http2=True needs the h2 package\n        return c.get(URL)\n\n\nclients = {\n    &quot;requests&quot;: lambda: requests.get(URL, verify=CA),\n    &quot;httpx, http2=True&quot;: httpx_h2,\n    &quot;curl_cffi, impersonate=chrome&quot;: lambda: curl.get(URL, impersonate=&quot;chrome&quot;, verify=CA),\n}\nfor name, send in clients.items():\n    seen = [send().json() for _ in range(10)]\n    distinct = {s[&quot;fp&quot;] for s in seen}\n    print(name.ljust(32), len(distinct), &quot;distinct in 10&quot;, seen[0][&quot;fp&quot;])\n    print(&quot; &quot; * 32, &quot;headers:&quot;, &quot; &quot;.join(seen[0][&quot;names&quot;]))<\/pre>\n<\/div>\n<p>For Chrome, keep the listener running with its output saved: python site.py &gt; frames.txt in the first window. The block below, in a second PowerShell window, starts Chrome eight times with a new profile each time and counts the different strings for the path \/fp.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># Eight separate Chrome starts against the listener, then a count of the strings it saw.\n$chrome = &quot;C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe&quot;\n1..8 | ForEach-Object {\n  $dir = Join-Path $env:TEMP &quot;h2fp-profile-$_&quot;  # a new profile each time\n  $p = Start-Process $chrome -ArgumentList &quot;--headless=new&quot;, &quot;--ignore-certificate-errors&quot;, &quot;--user-data-dir=$dir&quot;, &quot;https:\/\/127.0.0.1:12860\/fp&quot; -PassThru\n  Start-Sleep -Seconds 6\n  taskkill \/PID $p.Id \/T \/F 2&gt;$null | Out-Null\n}\n$seen = Get-Content frames.txt | Where-Object { $_ -match &quot; \/fp \\|&quot; } | ForEach-Object { ($_ -split &quot; \\| &quot;)[1] }\n&quot;{0} requests, {1} distinct string(s)&quot; -f $seen.Count, ($seen | Sort-Object -Unique).Count<\/pre>\n<\/div>\n<p>Each client gave one string over its ten connections (Windows 11, with Python 3.11.7, 3.13.7 and 3.14.0 in agreement). Chrome gave one string over eight starts, with one header order.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># What the listener recorded (Windows 11, Python 3.14.0)\nrequests 2.34.2                 no HTTP\/2: an HTTP\/1.1 request\nhttpx 0.28.1, http2=True        1:4096;2:0;4:65535;5:16384;3:100;6:65536|16777216|0|m,a,s,p\ncurl_cffi 0.17.0, chrome        1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p\nChrome 157.0.8103.78, headless  1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p<\/pre>\n<\/div>\n<p>Four things stand out. First, requests never asked for h2, so my listener answered it over HTTP\/1.1 and no frame exists to fingerprint. Second, httpx with http2=True differs from Chrome in its SETTINGS and WINDOW_UPDATE: a header table of 4096 against 65536, an initial window of 65535 against 6291456, a header list limit of 65536 against 262144, a maximum frame size and a stream limit that Chrome leaves out, and a WINDOW_UPDATE of 16777216 against 15663105. Third, curl_cffi with impersonate set to chrome sent the Chrome 157 string exactly, and its headers followed the order of a Chrome page request apart from one extra cache-control at the end.<\/p>\n<p>Fourth, a string describes a build and not a brand. Edge 158.0.4370.33 and Chromium 159.0.8154.6 from Playwright sent the Chrome 157 string. Chromium 145.0.7632.6 and 147.0.7727.15 from Playwright added a fifth setting whose id had the GREASE shape (every second hex digit an a) and whose value changed on each connection, three captures with three different pairs. My exact-string rule would refuse those two builds. The same Chrome also ordered the headers of its favicon request differently from those of the page request, in three of three starts, so header order belongs to the request type as well as the client.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 3: which values a Python option can change<\/h2>\n<p>Each client reaches a different layer. I changed one option at a time and read the result on the listener (Python 3.14.0, requests 2.34.2, httpx 0.28.1, curl_cffi 0.17.0 with its bundled curl-impersonate 2.3.1). For requests, a session with its headers cleared kept the order I gave, except that urllib3 added host and accept-encoding in front, and user-agent as well when my list had none.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># What each client lets you change (httpx 0.28.1, curl_cffi 0.17.0)\npart of the string         httpx                                      curl_cffi\nHTTP version               http2=True, with the h2 package            http_version, or the profile\nSETTINGS, WINDOW_UPDATE    no option that I found                     the profile, or the akamai string\nPRIORITY frames            none sent                                  none sent, even from my akamai string\npseudo-header order        always m,a,s,p                             the profile, or the akamai string\nheader order               yes, if the list has accept-encoding       set by the profile<\/pre>\n<\/div>\n<p>The curl_cffi profiles are not equally fresh, so compare a profile with the browser you copy. The listener recorded these strings for the profiles I tried, and Edge 158 sent the Chrome string, not the one in the edge profile.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># curl_cffi 0.17.0 profiles as the listener recorded them (Python 3.14.0)\nedge (edge101)        1:65536;3:1000;4:6291456;6:262144|15663105|0|m,a,s,p\nfirefox (firefox155)  1:65536;2:0;4:131072;5:16384|12517377|0|m,p,a,s\nsafari (safari270)    2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p<\/pre>\n<\/div>\n<p>The Firefox profile has no PRIORITY frames, while the Firefox 53 in the paper sent five, and I captured no live Firefox to say what a current one sends. The akamai argument takes the string itself. With the Firefox 53 string from the paper and no profile, the listener recorded the settings, the WINDOW_UPDATE and the pseudo-header order as given, but the five PRIORITY frames came back as 0, so this build ignores that part of a string. Adding impersonate chrome gave the same string and the warning <code>Akamai fingerprint was altered after impersonated version was set.<\/code> curl_cffi with no impersonate at all sent the Chrome string too, and so did its low-level Curl class, so the default sits in the bundled libcurl.<\/p>\n<p>httpx has no option for the SETTINGS and WINDOW_UPDATE rows, because httpcore writes them. The next block replaces a private httpcore method with one that sends the Chrome values. It ran on httpcore 1.0.9.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># chrome_h2.py: give httpx the Chrome connection start. This replaces a private httpcore method.\nimport collections\nimport ssl\n\nimport h2.settings\nimport httpcore._sync.http2 as http2\nimport httpx\nfrom h2.settings import SettingCodes as S\n\n\ndef chrome_init(self, request):\n    settings = h2.settings.Settings(client=True, initial_values={\n        S.HEADER_TABLE_SIZE: 65536, S.ENABLE_PUSH: 0, S.INITIAL_WINDOW_SIZE: 6291456, S.MAX_HEADER_LIST_SIZE: 262144})\n    del settings[S.MAX_FRAME_SIZE], settings[S.ENABLE_CONNECT_PROTOCOL]  # Chrome sends neither\n    self._h2_state.local_settings = settings\n    self._h2_state.initiate_connection()\n    self._h2_state.decoder.max_allowed_table_size = 65536  # the table size we just announced\n    self._h2_state.increment_flow_control_window(15663105)  # the Chrome WINDOW_UPDATE\n    self._write_outgoing_data(request)\n    # httpcore wants a stream limit afterwards, and Chrome does not send one\n    settings._settings[S.MAX_CONCURRENT_STREAMS] = collections.deque([100])\n\n\nhttp2.HTTP2Connection._send_connection_init = chrome_init\n\nif __name__ == &quot;__main__&quot;:\n    with httpx.Client(http2=True, verify=ssl.create_default_context(cafile=&quot;cert.pem&quot;)) as client:\n        seen = client.get(&quot;https:\/\/127.0.0.1:12860\/fp&quot;).json()\n    print(seen[&quot;fp&quot;])<\/pre>\n<\/div>\n<p>With it, httpx sent exactly the Chrome string. Without the decoder line the first response failed with an httpx LocalProtocolError saying the encoder exceeded the maximum table size, because my listener used the 65536 table the patch announced. Passing the Chrome headers, accept-encoding included, as the headers argument of Client reproduced the Chrome header order. Treat the patch as a way to learn, not as a dependency: it replaces a private method, touches h2 internals, covers only the synchronous client and may break in any release.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">Step 4: block, solve and submit with the client that passes<\/h2>\n<p>Now the rule meets CapSkip. My site refuses every connection whose string differs from the Chrome string, so the page, the solve and the form post all go through one curl_cffi session with impersonate set to chrome. The first block finds the sitekey in the data-sitekey attribute of the widget div on the page this session just fetched. A script-drawn widget needs a different read that I did not test. Neither library sends a Referer on a form post by itself, so the helper sets one, because my mock refuses a form post without it. The timeout belongs to the constructor: passing timeout to recaptcha raised TypeError in my run, so the block sets recaptchaTimeout. The sitekey on my mock page is fake, so point SITE at a page you may test before you run this against a real CapSkip.<\/p>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># signup.py (part 1 of 2): one passing client for the page, the solve and the form post.\nimport os\nimport re\nimport ssl\nimport sys\nimport time\n\nimport httpx\nfrom curl_cffi import requests as curl\nfrom capskip import ApiException, CapSkip, NetworkException, TimeoutException, ValidationException\n\nSITE = os.environ.get(&quot;SITE&quot;, &quot;https:\/\/127.0.0.1:12860&quot;)\n# CapSkip listens on 8080 by default. In Server mode, use the address of that machine as host.\nsolver = CapSkip(host=&quot;127.0.0.1&quot;, port=int(os.environ.get(&quot;CAPSKIP_PORT&quot;, &quot;8080&quot;)), recaptchaTimeout=120)\n# The same client carries the page, and later the form post.\n# verify=cert.pem trusts only the mock listener: drop it for a site with a real certificate.\nclient = curl.Session(impersonate=&quot;chrome&quot;, verify=&quot;cert.pem&quot;)\n\n\ndef read_sitekey():\n    page = client.get(SITE + &quot;\/signup&quot;)\n    if page.status_code == 403 and not page.text:\n        raise RuntimeError(&quot;blocked before any HTML: check the connection first&quot;)\n    found = re.search(r&quot;data-sitekey=[\\&quot;']([^\\&quot;']+)[\\&quot;']&quot;, page.text)\n    if not found:\n        raise RuntimeError(&quot;no data-sitekey on the page (HTTP %d)&quot; % page.status_code)\n    return found.group(1)\n\n\ndef submit(sender, token):\n    # a browser sends Referer on a form post, and neither library adds it for you\n    return sender.post(SITE + &quot;\/login&quot;, data={&quot;email&quot;: &quot;alice@example.com&quot;, &quot;g-recaptcha-response&quot;: token},\n                       headers={&quot;referer&quot;: SITE + &quot;\/signup&quot;})<\/pre>\n<\/div>\n<div data-no-translation>\n<pre data-enlighter-language=\"python\" class=\"EnlighterJSRAW\"># signup.py (part 2 of 2, same file): read the sitekey, solve once, post right away.\ntry:\n    sitekey = read_sitekey()\n    started = time.time()\n    result = solver.recaptcha(sitekey, SITE + &quot;\/signup&quot;)\n    print(&quot;token of %d characters after %.1f s&quot; % (len(result[&quot;code&quot;]), time.time() - started))\n    if os.environ.get(&quot;TRY_FIRST&quot;) == &quot;httpx&quot;:  # the wrong way, to see what the rule does\n        with httpx.Client(http2=True, verify=ssl.create_default_context(cafile=&quot;cert.pem&quot;)) as plain:\n            wrong = submit(plain, result[&quot;code&quot;])\n        print(&quot;httpx form post:&quot;, wrong.status_code, repr(wrong.text))\n    reply = submit(client, result[&quot;code&quot;])\n    print(&quot;curl_cffi form post:&quot;, reply.status_code, reply.text)\nexcept ValidationException as err:\n    print(&quot;refused before sending:&quot;, err)\n    sys.exit(1)\nexcept ApiException as err:\n    print(&quot;CapSkip answered:&quot;, err)\n    sys.exit(1)\nexcept TimeoutException as err:\n    print(&quot;no token in time:&quot;, err)\n    sys.exit(1)\nexcept NetworkException as err:\n    print(&quot;CapSkip not reachable:&quot;, err)\n    sys.exit(1)\nexcept RuntimeError as err:\n    print(&quot;failed:&quot;, err)\n    sys.exit(1)<\/pre>\n<\/div>\n<div data-no-translation>\n<pre data-enlighter-language=\"bash\" class=\"EnlighterJSRAW\"># PowerShell: run the flow once, then once with the form post tried through httpx first\npython signup.py\n$env:TRY_FIRST = &quot;httpx&quot;\npython signup.py<\/pre>\n<\/div>\n<p>Part 2 of signup.py asks CapSkip for one token and uses it at once. The call is recaptcha(sitekey, url) from capskip 1.8.0. It returns a dict whose token sits under <code>result[&quot;code&quot;]<\/code>, and that value belongs in the g-recaptcha-response field.<\/p>\n<p>My mock of CapSkip was set to a 2 second solve. The call returned a 128 character token after 3.8 seconds on each of Python 3.11.7, 3.13.7 and 3.14.0, since the SDK polls at growing intervals. The form post through curl_cffi got HTTP 200 and my site saved it. With TRY_FIRST set, the form post through httpx got 403 and an empty body, because my rule refuses the connection before it reads the form. My mock had not spent the token, so the curl_cffi form post that followed saved it. A real site could count the token as used after any form post that reaches it, which is why the solve comes last.<\/p>\n<p>I also gave the SDK a mock that never answers. A recaptchaTimeout of 4 ended in TimeoutException after 7.76 seconds and one of 12 after 12.76, since the deadline is compared with the clock only after each sleep. A parameter that reCAPTCHA v2 does not take, such as userAgent, is refused with ValidationException before anything is sent. The SDK reaches CapSkip over plain HTTP\/1.1 on its own connection, which never touches the frames of the form post.<\/p>\n<h2 style=\"font-size:1.6rem;line-height:1.35;\">FAQ<\/h2>\n<details style=\"border:1px solid #e2e5ee;border-radius:10px;padding:14px 18px;margin:0 0 12px;\">\n<summary style=\"cursor:pointer;\">\n<h3 style=\"font-size:1.15rem;line-height:1.4;display:inline;margin:0;\">Does CapSkip change the frames my script sends?<\/h3>\n<\/summary>\n<p style=\"margin:12px 0 0;\">No. CapSkip works on the CAPTCHA widget and returns a token, and it has no part in how your client opens a connection. The frames of the form post belong to your client alone.<\/p>\n<\/details>\n<details style=\"border:1px solid #e2e5ee;border-radius:10px;padding:14px 18px;margin:0 0 12px;\">\n<summary style=\"cursor:pointer;\">\n<h3 style=\"font-size:1.15rem;line-height:1.4;display:inline;margin:0;\">Can CapSkip run on a different machine from my script?<\/h3>\n<\/summary>\n<p style=\"margin:12px 0 0;\">Yes, in Server mode. A Windows machine you control then answers the API for other machines, and your script passes that machine as host. Starting Server mode also leaves the port reachable from any address, so a narrower allow rule achieves nothing. Fence it with a Windows Firewall block rule for every range you do not trust, because Windows Firewall applies block rules first, which I did not test here, and keep the port closed on your router. No second machine took part in my runs.<\/p>\n<\/details>\n<details style=\"border:1px solid #e2e5ee;border-radius:10px;padding:14px 18px;margin:0 0 12px;\">\n<summary style=\"cursor:pointer;\">\n<h3 style=\"font-size:1.15rem;line-height:1.4;display:inline;margin:0;\">What does a matching connection start not fix?<\/h3>\n<\/summary>\n<p style=\"margin:12px 0 0;\">Your IP address, which the <a href=\"https:\/\/capskip.com\/captcha-solver-proxy\/\">CAPTCHA solver proxy<\/a> guide covers, and what your script does after the connection starts. An empty 403, which is what my mock returns, is a refusal before any page exists, so no widget is there for CapSkip to solve. The <a href=\"https:\/\/capskip.com\/captcha-or-block\/\">CAPTCHA or block<\/a> guide shows how to tell that from a challenge. I captured no TLS, ran no live Firefox or Safari and tested no real site.<\/p>\n<\/details>\n<p>Once your connection start passes and the site shows a widget, a <a href=\"https:\/\/capskip.com\/\">captcha solver<\/a> that runs on your own PC under a flat license turns it into a token, and a rejected form post costs seconds and no per-solve fee. The <a href=\"https:\/\/capskip.com\/recaptcha-v2-python\/\">reCAPTCHA v2 in Python<\/a> guide covers that solve in detail. Your PC runs the same call for every type, and the <a href=\"https:\/\/capskip.com\/python-captcha-solver\/\">Python CAPTCHA solver<\/a> page lists the types it supports.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>httpx \u5efa\u7acb HTTP\/2 \u8fde\u63a5\u7684\u65b9\u5f0f\u4e0e Chrome \u4e0d\u540c\uff0ccurl_cffi \u80fd\u5b8c\u5168\u590d\u5236 Chrome\uff0c\u800c requests \u6839\u672c\u4e0d\u4f7f\u7528 HTTP\/2\u3002\u4e00\u4e2a\u5c0f\u578b\u76d1\u542c\u5668\u8bb0\u5f55\u8fd9\u4e9b\u5e27\uff0c\u663e\u793a\u54ea\u4e9b Python \u9009\u9879\u4f1a\u6539\u53d8\u5b83\u4eec\uff0c\u4ee5\u53ca CapSkip \u5728\u54ea\u91cc\u4ecb\u5165\u3002<\/p>","protected":false},"author":1,"featured_media":28743,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"rank_math_title":"HTTP2 Fingerprint in Python: Measured | CapSkip","rank_math_description":"Record the first HTTP\/2 frames of httpx, curl_cffi and Chrome and read your http2 fingerprint in Python from a listener you run. Copy the code.","rank_math_focus_keyword":"http2 fingerprint in python","footnotes":""},"categories":[70],"tags":[],"class_list":["post-28745","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-captcha"],"_links":{"self":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts\/28745","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/comments?post=28745"}],"version-history":[{"count":1,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts\/28745\/revisions"}],"predecessor-version":[{"id":29208,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/posts\/28745\/revisions\/29208"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/media\/28743"}],"wp:attachment":[{"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/media?parent=28745"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/categories?post=28745"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/capskip.com\/zh\/wp-json\/wp\/v2\/tags?post=28745"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}