Python 中的 HTTP2 指纹:每个客户端到底发送什么

http2 fingerprint in python - HTTP2 Fingerprint in Python: What Each Client Really Sends

要在 Python 里读取你的 http2 指纹,就记录客户端在你控制的连接上发送的第一批帧,并按 Akamai 提出的格式写下来:按发送顺序排列的 SETTINGS 值、WINDOW_UPDATE 增量、所有 PRIORITY 帧,以及伪头部的顺序。在 Windows 11 上,开启 HTTP/2 的 httpx 发送的字符串与 Chrome 的字符串不同,curl_cffi 发送的与 Chrome 的字符串完全一致,而 requests 根本不发送 HTTP/2。下面依次是记录器、测量结果、Python 的哪个选项能改变什么,以及 CapSkip 介入的位置:它识别的是你的客户端通过之后你遇到的验证码,它从不改变任何一个帧。

你需要什么

  • Python 3.10 或更新版本:capskip 1.8.0、h2 4.4.1、hpack 4.2.0、requests 2.34.2 和 curl_cffi 0.17.0 在 python_requires 里都声明 3.10,而 httpx 0.28.1 声明 3.8,cryptography 50.0.2 声明 3.9。我在 3.11.7、3.13.7 和 3.14.0 上运行了每个 Python 代码块,3.10 上一个都没有运行过。
  • 一个装有下面这些包的虚拟环境。
  • 运行监听器的机器上的 Chrome,用于浏览器测量。我的是 157.0.8103.78,以新的无头模式启动。
  • CapSkip 5.7.0,只用于最后一步,运行在 Windows PC 上,如设置指南所述。下面每个 CapSkip 的结果都来自我在它自己的端口上写的 in.php 和 res.php 的模拟服务。我没有向真实应用发送任何任务,也没有向真实站点发送任何任务。
  • 一个 CapSkip 的地址。Local mode 把它保持在回环地址上,只有那台 PC 能访问。Server mode 监听网络地址,这样其他机器就能调用 API,正如设置指南中的 连接设置 一节所解释的。
# In PowerShell, in a new empty folder
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install capskip "httpx[http2]" curl_cffi requests cryptography

本指南里的允许规则和阻止规则是我写的,用来代替真实站点可能的做法。这里没有任何东西表明真实的厂商会根据所示的任何值进行拦截。在这些帧之前发生的 TLS 握手是单独的一层,由 Python 中的 TLS 指纹 指南负责。

第 1 步:在任何 HTTP 代码运行之前先记录第一批帧

HTTP 库会解析这些帧并把它们藏起来,所以要先读取字节。这个字符串有四个部分,用竖线连接。第一部分按发送顺序把 SETTINGS 列为 id:value 对,第二部分是 WINDOW_UPDATE 增量,第三部分把 PRIORITY 帧列为 stream:exclusive:depends-on:weight,第四部分按发送顺序给出伪头部的首字母。我遵循了 Akamai 白皮书,它定义了前三个部分,并加上了第四个。白皮书把缺失的 WINDOW_UPDATE 写作 00,我也一样。

把这个代码块保存为 fp.py。

# fp.py: read the first HTTP/2 frames of a connection and build an Akamai-style fingerprint.
from hpack import Decoder

PREFACE = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"


class Frames:
    """Feed it the raw bytes a client sends. It records and never answers."""

    def __init__(self):
        self.buf, self.ok = b"", None  # ok: did the 24 byte preface arrive?
        self.settings, self.update, self.priority = None, None, []
        self.names = None  # header names of the first request, in wire order
        self.block, self.decoder = b"", Decoder()

    def feed(self, data):
        self.buf += data
        if self.ok is None and len(self.buf) >= 24:
            self.ok = self.buf.startswith(PREFACE)
            self.buf = self.buf[24:]
        while self.ok and len(self.buf) >= 9:
            size, kind, flags = int.from_bytes(self.buf[:3], "big"), self.buf[3], self.buf[4]
            stream = int.from_bytes(self.buf[5:9], "big") & 0x7FFFFFFF
            if len(self.buf) < 9 + size:
                return
            body, self.buf = self.buf[9 : 9 + size], self.buf[9 + size :]
            self.frame(kind, flags, stream, body)

    def frame(self, kind, flags, stream, body):
        if self.names is not None:
            return  # only the frames before the first request count
        if kind == 4 and not flags & 1 and self.settings is None:  # SETTINGS, not an ack
            self.settings = [(int.from_bytes(body[i : i + 2], "big"), int.from_bytes(body[i + 2 : i + 6], "big")) for i in range(0, len(body), 6)]
        elif kind == 8 and stream == 0 and self.update is None:  # WINDOW_UPDATE on the connection
            self.update = int.from_bytes(body[:4], "big") & 0x7FFFFFFF
        elif kind == 2:  # PRIORITY: stream, exclusive bit, depends on, weight (the wire byte plus one)
            dep = int.from_bytes(body[:4], "big")
            self.priority.append((stream, dep >> 31, dep & 0x7FFFFFFF, body[4] + 1))
        elif kind == 1 or kind == 9:  # HEADERS, then CONTINUATION
            if kind == 1:
                if flags & 8:
                    body = body[1 : len(body) - body[0]]  # padding
                if flags & 0x20:  # a priority carried inside HEADERS is not part of the string
                    body = body[5:]
            self.block += body
            if flags & 4:  # END_HEADERS
                self.names = [n.decode("latin-1") for n, _ in self.decoder.decode(self.block, raw=True)]

    def akamai(self):
        s = ";".join("%d:%d" % kv for kv in self.settings or [])
        wu = "00" if self.update is None else str(self.update)  # the paper writes 00 for no frame
        p = ",".join("%d:%d:%d:%d" % t for t in self.priority) or "0"
        ps = ",".join(n[1] for n in self.names or [] if n.startswith(":"))
        return "|".join([s, wu, p, ps])

我对照白皮书检查了它。用 7 字节的块重放白皮书里记录的帧序列(Mac 和 Android 上的 Firefox 53、Chrome 58、Edge 14、OkHttp 3.6、一个 Go 客户端、curl 7.54 和 nghttp2 1.22),重现了全部八个打印出来的字符串。这证明代码遵循了白皮书,而不是证明当前的客户端仍在发送那些帧,那是测量要回答的问题。

监听器是 site.py 的三个代码块,按顺序。它的规则只放行帧与第 2 步测得的 Chrome 字符串相匹配的连接,路径 /fp 回显任何客户端发送的内容。

# site.py (part 1 of 3): imports, the mock rule and the mock pages.
import datetime, ipaddress, json, os, pathlib, socket, ssl, threading
import h2.config, h2.connection, h2.events, h2.exceptions
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.x509.oid import NameOID
from fp import Frames

PORT = 12860
# The mock rule: only a connection whose first frames match this string gets the page.
ALLOW = {"1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p"}
PAGE = '<form method="post" action="/login"><input name="email"><div class="g-recaptcha" data-sitekey="6LeMOCKMOCKMOCKMOCKMOCKMOCKMOCKMOCKMOCK0"></div></form>'
spent = set()  # tokens this site has already accepted


def make_cert():
    key = ec.generate_private_key(ec.SECP256R1())
    name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "localhost")])
    now = datetime.datetime.now(datetime.timezone.utc)
    cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
            .serial_number(x509.random_serial_number()).not_valid_before(now - datetime.timedelta(minutes=5))
            .not_valid_after(now + datetime.timedelta(days=30))
            .add_extension(x509.SubjectAlternativeName([x509.DNSName("localhost"), x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]), False)
            .add_extension(x509.BasicConstraints(ca=True, path_length=None), True)
            .add_extension(x509.KeyUsage(True, False, False, False, False, True, True, False, False), True)
            .sign(key, hashes.SHA256()))
    pathlib.Path("cert.pem").write_bytes(cert.public_bytes(serialization.Encoding.PEM))
    pathlib.Path("key.pem").write_bytes(key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))


def answer(method, path, headers, body, fp, names):
    """Return (status, content type, text). The rule runs first, except on /fp, which only echoes."""
    verdict = "ALLOWED" if fp in ALLOW else "BLOCKED"
    print(verdict, method, path, "|", fp, "|", " ".join(names), flush=True)
    if path == "/fp":
        return 200, "application/json", json.dumps({"fp": fp, "names": names})
    if verdict == "BLOCKED":
        return 403, "text/plain", ""
    if method == "GET" and path == "/signup":
        return 200, "text/html", PAGE
    if method == "POST" and path == "/login":
        if not headers.get("referer", "").startswith("https://127.0.0.1:%d/" % PORT):
            return 403, "text/plain", "no referer"
        token = dict(p.split("=", 1) for p in body.split("&") if "=" in p).get("g-recaptcha-response", "")
        if token and token not in spent:
            spent.add(token)
            return 200, "text/html", "<p>saved</p>"
        return 200, "text/html", "<p>captcha check failed</p>"
    return 404, "text/plain", ""
# 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.
def serve_h2(tls):
    frames = Frames()
    conn = h2.connection.H2Connection(h2.config.H2Configuration(client_side=False, header_encoding="utf-8"))
    conn.initiate_connection()
    tls.sendall(conn.data_to_send())
    reqs = {}
    while True:
        data = tls.recv(65535)
        if not data:
            return
        frames.feed(data)  # record first, then let the h2 package see the same bytes
        for ev in conn.receive_data(data):
            if isinstance(ev, h2.events.RequestReceived):
                reqs[ev.stream_id] = [dict(ev.headers), b"", [n for n, _ in ev.headers]]
            elif isinstance(ev, h2.events.DataReceived):
                reqs[ev.stream_id][1] += ev.data
                conn.acknowledge_received_data(ev.flow_controlled_length, ev.stream_id)
            elif isinstance(ev, h2.events.StreamEnded):
                headers, body, names = reqs[ev.stream_id]
                if ev.stream_id == 1:
                    names = frames.names  # the first request, straight from the wire
                status, ctype, text = answer(headers[":method"], headers[":path"], headers, body.decode(), frames.akamai(), names)
                raw = text.encode()
                conn.send_headers(ev.stream_id, [(":status", str(status)), ("content-type", ctype), ("content-length", str(len(raw)))])
                conn.send_data(ev.stream_id, raw, end_stream=True)
        tls.sendall(conn.data_to_send())


def serve_h1(tls):
    buf = b""
    while b"\r\n\r\n" not in buf:
        chunk = tls.recv(65535)
        if not chunk:
            return
        buf += chunk
    head, _, rest = buf.partition(b"\r\n\r\n")
    lines = head.decode("latin-1").split("\r\n")
    method, path, _ = lines[0].split(" ", 2)
    pairs = [l.split(":", 1) for l in lines[1:]]
    headers = {k.strip().lower(): v.strip() for k, v in pairs}
    while len(rest) < int(headers.get("content-length", 0)):
        rest += tls.recv(65535)
    status, ctype, text = answer(method, path, headers, rest.decode(), "http/1.1", [k.strip().lower() for k, _ in pairs])
    raw = text.encode()
    tls.sendall(("HTTP/1.1 %d X\r\ncontent-type: %s\r\ncontent-length: %d\r\nconnection: close\r\n\r\n" % (status, ctype, len(raw))).encode() + raw)
# site.py (part 3 of 3, same file): accept connections and start the listener.
def handle(sock):
    tls = None
    try:
        tls = CTX.wrap_socket(sock, server_side=True)
        (serve_h2 if tls.selected_alpn_protocol() == "h2" else serve_h1)(tls)
    except (OSError, ssl.SSLError, h2.exceptions.ProtocolError):
        pass
    finally:
        (tls or sock).close()


if __name__ == "__main__":
    if not os.path.exists("cert.pem"):
        make_cert()
    CTX = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    CTX.load_cert_chain("cert.pem", "key.pem")
    CTX.set_alpn_protocols(["h2", "http/1.1"])
    server = socket.create_server(("127.0.0.1", PORT))
    print("listening on", PORT, flush=True)
    while True:
        threading.Thread(target=handle, args=(server.accept()[0],), daemon=True).start()

第 2 步:用每个客户端发送同样的请求

在一个窗口里用 python site.py 启动监听器。把下一个代码块保存为 clients.py,在第二个窗口里运行。每个客户端建立十次新连接,所以变化的指纹会表现为不止一个不同的字符串。

# clients.py: ten new connections per client to the mock site, then print what it recorded.
import ssl

import httpx
import requests
from curl_cffi import requests as curl

URL = "https://127.0.0.1:12860/fp"
CA = "cert.pem"  # the certificate site.py wrote
CTX = ssl.create_default_context(cafile=CA)  # httpx 0.28.1 warns about verify given as a path


def httpx_h2():
    with httpx.Client(http2=True, verify=CTX) as c:  # http2=True needs the h2 package
        return c.get(URL)


clients = {
    "requests": lambda: requests.get(URL, verify=CA),
    "httpx, http2=True": httpx_h2,
    "curl_cffi, impersonate=chrome": lambda: curl.get(URL, impersonate="chrome", verify=CA),
}
for name, send in clients.items():
    seen = [send().json() for _ in range(10)]
    distinct = {s["fp"] for s in seen}
    print(name.ljust(32), len(distinct), "distinct in 10", seen[0]["fp"])
    print(" " * 32, "headers:", " ".join(seen[0]["names"]))

对于 Chrome,让监听器保持运行并保存它的输出:在第一个窗口里运行 python site.py > frames.txt。下面的代码块在第二个 PowerShell 窗口里,用每次都全新的配置文件启动 Chrome 八次,并统计路径 /fp 上不同字符串的数量。

# Eight separate Chrome starts against the listener, then a count of the strings it saw.
$chrome = "C:\Program Files\Google\Chrome\Application\chrome.exe"
1..8 | ForEach-Object {
  $dir = Join-Path $env:TEMP "h2fp-profile-$_"  # a new profile each time
  $p = Start-Process $chrome -ArgumentList "--headless=new", "--ignore-certificate-errors", "--user-data-dir=$dir", "https://127.0.0.1:12860/fp" -PassThru
  Start-Sleep -Seconds 6
  taskkill /PID $p.Id /T /F 2>$null | Out-Null
}
$seen = Get-Content frames.txt | Where-Object { $_ -match " /fp \|" } | ForEach-Object { ($_ -split " \| ")[1] }
"{0} requests, {1} distinct string(s)" -f $seen.Count, ($seen | Sort-Object -Unique).Count

每个客户端在它的十次连接里都只给出一个字符串(Windows 11,Python 3.11.7、3.13.7 和 3.14.0 的结果一致)。Chrome 在八次启动里给出一个字符串,请求头顺序也只有一种。

# What the listener recorded (Windows 11, Python 3.14.0)
requests 2.34.2                 no HTTP/2: an HTTP/1.1 request
httpx 0.28.1, http2=True        1:4096;2:0;4:65535;5:16384;3:100;6:65536|16777216|0|m,a,s,p
curl_cffi 0.17.0, chrome        1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p
Chrome 157.0.8103.78, headless  1:65536;2:0;4:6291456;6:262144|15663105|0|m,a,s,p

有四点值得注意。第一,requests 从未请求 h2,所以我的监听器用 HTTP/1.1 应答了它,没有任何帧可供做指纹。第二,http2=True 的 httpx 在 SETTINGS 和 WINDOW_UPDATE 上与 Chrome 不同:头表 4096 对 65536,初始窗口 65535 对 6291456,头列表上限 65536 对 262144,Chrome 没有写的最大帧大小和流上限,以及 WINDOW_UPDATE 16777216 对 15663105。第三,impersonate 设为 chrome 的 curl_cffi 发送的就是 Chrome 157 的字符串,它的请求头遵循 Chrome 页面请求的顺序,只是末尾多了一个 cache-control。

第四,字符串描述的是一个构建,而不是一个品牌。Edge 158.0.4370.33 和 Playwright 的 Chromium 159.0.8154.6 发送的是 Chrome 157 的字符串。Playwright 的 Chromium 145.0.7632.6 和 147.0.7727.15 增加了第五个设置,它的 id 具有 GREASE 的形态(每隔一位十六进制数字就是一个 a),值在每次连接时都会变,三次捕获得到三对不同的值。我的精确字符串规则会拒绝这两个构建。同一个 Chrome 对 favicon 请求的请求头排序也与页面请求不同,三次启动都是如此,所以请求头顺序既属于客户端,也属于请求类型。

第 3 步:Python 的哪个选项能改变哪些值

每个客户端触及的层不同。我一次只改一个选项,并在监听器上读取结果(Python 3.14.0、requests 2.34.2、httpx 0.28.1、curl_cffi 0.17.0 及其自带的 curl-impersonate 2.3.1)。对于 requests,清空了请求头的 session 保留了我给出的顺序,只是 urllib3 在前面加了 host 和 accept-encoding,在我的列表里没有 user-agent 时也加上它。

# What each client lets you change (httpx 0.28.1, curl_cffi 0.17.0)
part of the string         httpx                                      curl_cffi
HTTP version               http2=True, with the h2 package            http_version, or the profile
SETTINGS, WINDOW_UPDATE    no option that I found                     the profile, or the akamai string
PRIORITY frames            none sent                                  none sent, even from my akamai string
pseudo-header order        always m,a,s,p                             the profile, or the akamai string
header order               yes, if the list has accept-encoding       set by the profile

curl_cffi 的配置档新旧程度不同,所以要把配置档与你复制的浏览器作比较。监听器记录了我试过的配置档的这些字符串,Edge 158 发送的是 Chrome 的字符串,而不是 edge 配置档里的那个。

# curl_cffi 0.17.0 profiles as the listener recorded them (Python 3.14.0)
edge (edge101)        1:65536;3:1000;4:6291456;6:262144|15663105|0|m,a,s,p
firefox (firefox155)  1:65536;2:0;4:131072;5:16384|12517377|0|m,p,a,s
safari (safari270)    2:0;3:100;4:2097152;9:1|10420225|0|m,s,a,p

Firefox 配置档没有 PRIORITY 帧,而白皮书里的 Firefox 53 发送了五个,而且我没有捕获真实的 Firefox,所以说不出当前版本发送什么。akamai 参数接受字符串本身。用白皮书里的 Firefox 53 字符串、不用配置档时,监听器按给定的内容记录了设置、WINDOW_UPDATE 和伪头部顺序,但五个 PRIORITY 帧回来时是 0,所以这个构建忽略字符串的这一部分。加上 impersonate chrome 得到相同的字符串,以及这条警告 Akamai fingerprint was altered after impersonated version was set. 没有任何 impersonate 的 curl_cffi 也发送 Chrome 的字符串,它的底层 Curl 类也一样,所以这个默认值在自带的 libcurl 里。

httpx 没有针对 SETTINGS 和 WINDOW_UPDATE 行的选项,因为是 httpcore 写它们。下一个代码块用一个发送 Chrome 值的方法替换 httpcore 的一个私有方法。它在 httpcore 1.0.9 上运行过。

# chrome_h2.py: give httpx the Chrome connection start. This replaces a private httpcore method.
import collections
import ssl

import h2.settings
import httpcore._sync.http2 as http2
import httpx
from h2.settings import SettingCodes as S


def chrome_init(self, request):
    settings = h2.settings.Settings(client=True, initial_values={
        S.HEADER_TABLE_SIZE: 65536, S.ENABLE_PUSH: 0, S.INITIAL_WINDOW_SIZE: 6291456, S.MAX_HEADER_LIST_SIZE: 262144})
    del settings[S.MAX_FRAME_SIZE], settings[S.ENABLE_CONNECT_PROTOCOL]  # Chrome sends neither
    self._h2_state.local_settings = settings
    self._h2_state.initiate_connection()
    self._h2_state.decoder.max_allowed_table_size = 65536  # the table size we just announced
    self._h2_state.increment_flow_control_window(15663105)  # the Chrome WINDOW_UPDATE
    self._write_outgoing_data(request)
    # httpcore wants a stream limit afterwards, and Chrome does not send one
    settings._settings[S.MAX_CONCURRENT_STREAMS] = collections.deque([100])


http2.HTTP2Connection._send_connection_init = chrome_init

if __name__ == "__main__":
    with httpx.Client(http2=True, verify=ssl.create_default_context(cafile="cert.pem")) as client:
        seen = client.get("https://127.0.0.1:12860/fp").json()
    print(seen["fp"])

有了它,httpx 发送的恰好就是 Chrome 的字符串。没有 decoder 那一行时,第一个响应以 httpx 的 LocalProtocolError 失败,说 encoder 超过了最大表大小,因为我的监听器使用了补丁宣布的 65536 表。把 Chrome 的请求头(包括 accept-encoding)作为 Client 的 headers 参数传入,重现了 Chrome 的请求头顺序。把这个补丁当作学习的方式,而不是依赖:它替换了一个私有方法,触及 h2 的内部,只覆盖同步客户端,在任何版本里都可能失效。

第 4 步:用能通过的客户端完成拦截、识别和提交

现在规则遇上了 CapSkip。我的站点会拒绝每个字符串与 Chrome 字符串不同的连接,所以页面、识别和表单 POST 请求都通过同一个 impersonate 设为 chrome 的 curl_cffi session 完成。第一个代码块从这个 session 刚获取的页面中,在小组件 div 的 data-sitekey 属性里找到 sitekey。由脚本绘制的小组件需要另一种读取方式,我没有测试。两个库都不会自己在表单 POST 请求上发送 Referer,所以辅助函数设置了一个,因为我的模拟服务拒绝没有它的表单 POST 请求。超时属于构造函数:把 timeout 传给 recaptcha 在我的运行中引发了 TypeError,所以代码块设置的是 recaptchaTimeout。我的模拟页面上的 sitekey 是假的,所以在对着真实的 CapSkip 运行之前,请把 SITE 指向一个你可以测试的页面。

# signup.py (part 1 of 2): one passing client for the page, the solve and the form post.
import os
import re
import ssl
import sys
import time

import httpx
from curl_cffi import requests as curl
from capskip import ApiException, CapSkip, NetworkException, TimeoutException, ValidationException

SITE = os.environ.get("SITE", "https://127.0.0.1:12860")
# CapSkip listens on 8080 by default. In Server mode, use the address of that machine as host.
solver = CapSkip(host="127.0.0.1", port=int(os.environ.get("CAPSKIP_PORT", "8080")), recaptchaTimeout=120)
# The same client carries the page, and later the form post.
# verify=cert.pem trusts only the mock listener: drop it for a site with a real certificate.
client = curl.Session(impersonate="chrome", verify="cert.pem")


def read_sitekey():
    page = client.get(SITE + "/signup")
    if page.status_code == 403 and not page.text:
        raise RuntimeError("blocked before any HTML: check the connection first")
    found = re.search(r"data-sitekey=[\"']([^\"']+)[\"']", page.text)
    if not found:
        raise RuntimeError("no data-sitekey on the page (HTTP %d)" % page.status_code)
    return found.group(1)


def submit(sender, token):
    # a browser sends Referer on a form post, and neither library adds it for you
    return sender.post(SITE + "/login", data={"email": "[email protected]", "g-recaptcha-response": token},
                       headers={"referer": SITE + "/signup"})
# signup.py (part 2 of 2, same file): read the sitekey, solve once, post right away.
try:
    sitekey = read_sitekey()
    started = time.time()
    result = solver.recaptcha(sitekey, SITE + "/signup")
    print("token of %d characters after %.1f s" % (len(result["code"]), time.time() - started))
    if os.environ.get("TRY_FIRST") == "httpx":  # the wrong way, to see what the rule does
        with httpx.Client(http2=True, verify=ssl.create_default_context(cafile="cert.pem")) as plain:
            wrong = submit(plain, result["code"])
        print("httpx form post:", wrong.status_code, repr(wrong.text))
    reply = submit(client, result["code"])
    print("curl_cffi form post:", reply.status_code, reply.text)
except ValidationException as err:
    print("refused before sending:", err)
    sys.exit(1)
except ApiException as err:
    print("CapSkip answered:", err)
    sys.exit(1)
except TimeoutException as err:
    print("no token in time:", err)
    sys.exit(1)
except NetworkException as err:
    print("CapSkip not reachable:", err)
    sys.exit(1)
except RuntimeError as err:
    print("failed:", err)
    sys.exit(1)
# PowerShell: run the flow once, then once with the form post tried through httpx first
python signup.py
$env:TRY_FIRST = "httpx"
python signup.py

signup.py 的第 2 部分向 CapSkip 请求一个 token 并立刻使用它。调用是 capskip 1.8.0 的 recaptcha(sitekey, url)。它返回一个字典,token 放在键 result["code"]下,这个值要放进 g-recaptcha-response 字段。

我的 CapSkip 模拟服务设置为 2 秒识别。在 Python 3.11.7、3.13.7 和 3.14.0 上,调用都在 3.8 秒后返回一个 128 个字符的 token,因为 SDK 以逐渐增大的间隔轮询。通过 curl_cffi 的表单 POST 请求得到 HTTP 200,我的站点保存了它。设置 TRY_FIRST 时,通过 httpx 的表单 POST 请求得到 403 和空正文,因为我的规则在读取表单之前就拒绝了连接。我的模拟服务没有消耗 token,所以随后的 curl_cffi 表单 POST 请求保存了它。真实站点可能在任何到达它的表单 POST 请求之后就把 token 算作已用,所以识别要放在最后。

我还给 SDK 一个永不应答的模拟服务。recaptchaTimeout 为 4 时,在 7.76 秒后以 TimeoutException 结束,为 12 时在 12.76 秒后结束,因为截止时间只在每次休眠之后才与时钟比较。reCAPTCHA v2 不接受的参数(例如 userAgent),会在发出任何东西之前被 ValidationException 拒绝。SDK 通过它自己的连接,用普通的 HTTP/1.1 访问 CapSkip,这从不触及表单 POST 请求的帧。

常见问题

CapSkip 会改变我的脚本发送的帧吗?

不会。CapSkip 处理的是验证码小组件并返回一个 token,它不参与你的客户端如何建立连接。表单 POST 请求的帧只属于你的客户端。

CapSkip 能运行在与我的脚本不同的机器上吗?

可以,在 Server mode 下。由你掌控的一台 Windows 机器就会为其他机器应答 API,你的脚本把那台机器作为 host 传入。启动 Server mode 也会让端口可以从任何地址访问,所以更窄的允许规则起不到任何作用。请用一条针对你不信任的每个范围的 Windows Firewall 阻止规则把它围起来,因为 Windows Firewall 会先应用阻止规则,这一点我没有在这里测试过,并且在你的路由器上保持这个端口关闭。我的运行中没有第二台机器参与。

匹配的连接开头没有解决什么问题?

你的 IP 地址(相关内容见 验证码识别代理 指南),以及连接建立之后你的脚本做的事。像我的模拟服务返回的那种空的 403,是在任何页面存在之前就作出的拒绝,所以那里没有小组件供 CapSkip 识别。要把它与挑战区分开,请看 验证码还是封锁 指南。我没有捕获 TLS,没有运行真实的 Firefox 或 Safari,也没有测试任何真实站点。

一旦你的连接开头通过,而站点显示一个小组件,一个运行在你自己 PC 上、统一授权的 验证码识别工具 会把它变成 token,被拒绝的表单 POST 请求只花几秒,不按次收费。 用 Python 识别 reCAPTCHA v2 指南详细讲了这次识别。你的 PC 对每种类型运行同样的调用,而 Python 验证码识别工具 页面列出了它支持的类型。