跳转到主要内容
指南

IPRoyal 住宅代理配合 NSLSolver:用 Python 和 Node.js 获取 Kasada 请求头、Akamai Cookie 与 cf_clearance

NSLSolver 团队发布于 9 分钟阅读

IPRoyal 住宅代理的配置方式与多数服务商不同:用户名保持不变,从国家到粘性会话的所有选项都追加在密码后面。本文用这种格式把 IPRoyal 代理交给 NSLSolver,让 Kasada x-kpsdk 请求头、Akamai _abck cookie 和 Cloudflare cf_clearance cookie 都在你自己的请求随后使用的 IP 上获得,并提供 Python 与 Node.js 代码。

NSLSolver 在服务端求解,不使用浏览器,只对成功的求解计费。Cloudflare Challenge、reCAPTCHA v3 和 Akamai 必须使用代理,因为令牌或 cookie 属于获得它的 IP。IPRoyal 的 _killswitch-1 选项在这里特别有用:粘性 IP 丢失时它会明确报错,而不是悄悄替换。

IPRoyal 住宅代理格式速览

网关
geo.iproyal.com:12321(HTTP/HTTPS),:32325(SOCKS5)
认证
USERNAME:PASSWORD_<选项>_<选项>...
粘性会话
_session-<恰好 8 位字母数字>
会话时长
_lifetime-30m(1 秒至 7 天,单一单位)
地理定位
_country-gb _city-london _state-california(配合 _country-us) _region-europe
完整示例
http://USERNAME:PASSWORD_country-gb_session-a1b2c3d4_lifetime-30m@geo.iproyal.com:12321

来自 IPRoyal 住宅代理文档(docs.iproyal.com),2026 年 12 月 1 日核对。USERNAME 与 PASSWORD 为 IPRoyal 控制台中的代理凭据。

哪些 NSLSolver 求解需要 IPRoyal 代理?

把 IPRoyal 代理 URL 填入 POST https://api.nslsolver.com/solve 的 proxy 字段,并让你自己的请求走完全相同的 URL。由于会话写在密码中,密码字符串的任何改动(哪怕只是选项顺序)都可能变成另一个会话。

求解类型代理与 IP 绑定的内容NSLSolver 每 1,000 次价格
Cloudflare Challenge必需cf_clearance cookie$1.00
Akamai Bot Manager(测试版)必需_abck 与 bm_sz cookie$2.00
reCAPTCHA v3必需分数取决于 IP$1.00
Kasada可选,建议使用x-kpsdk-ct 会话$1.50
Cloudflare Turnstile可选(默认无需代理)默认无$0.80

只对成功的求解计费。IPRoyal 按你的 IPRoyal 套餐单独收取代理流量费用。

IPRoyal 基于密码的定位方式

IPRoyal 住宅代理不改动用户名,选项以 _键-值 的形式追加到密码后面:PASSWORD_country-gb_session-a1b2c3d4_lifetime-30m。不带 _session 时,每个请求都会轮换到新 IP。geo.iproyal.com 会自动选择就近的网关区域;IPRoyal 还列出了 us.proxy.iproyal.com、sg.proxy.iproyal.com 等区域主机,端口相同。

有两条规则最容易出错。会话值必须是恰好 8 位的随机字母数字字符串,所以 UUID 或工作进程名都不行。_lifetime 只能使用一个单位,范围 1 秒至 7 天:30m 或 2h 可以,1h30m 这样的组合值不行。

选项示例IPRoyal 文档说明
_country-_country-gb小写 ISO 代码。逗号列表(_country-dk,it,ie)会随机选一个。
_city-_city-london同时需要设置国家。
_state-_state-california仅限美国,配合 _country-us。
_region-_region-europeeurope、northamerica 等大区。
_session-_session-a1b2c3d4恰好 8 位字母数字;保持同一 IP。
_lifetime-_lifetime-30m1 秒至 7 天,只能用一个单位。
_killswitch-1_killswitch-1粘性 IP 不可用时返回 HTTP 410,而不是轮换。

IPRoyal 还提供 _forcerandom-1 和 IP 白名单(在控制台中设置,之后只用 host:port 连接)。

粘性会话、killswitch 与 cf_clearance 回放

cf_clearance 只在获得它的 IP 上、且只在网站的 Challenge Passage 时长内(默认 30 分钟)有效。Akamai 的 _abck 同理,Kasada 也要求 x-kpsdk-ct 会话保持在同一个 IP 上。因此本文的每个流程都使用 IPRoyal 粘性会话,lifetime 不短于结果的复用时间:_lifetime-30m 对应默认的 Challenge Passage。

默认情况下,粘性 IP 消失时 IPRoyal 会悄悄给会话换一个 IP。对与 IP 绑定的 cookie 来说这是最糟糕的情况:下一个请求带着一个从未获得该 cookie 的 IP 发出,网站会返回挑战或 403。加上 _killswitch-1 后,网关会返回 HTTP 410,下面的代码捕获该错误,开启新会话并重新求解。

地理位置也应保持不变。求解和回放使用相同的 _country(如果设置了 _city 也一样),对于 Cloudflare Challenge 再传入与该国家相符的 accept_language。_country-dk,it,ie 这种随机国家列表适合轮换流量,但不利于粘性会话中保持一致的身份。

Python:在带 killswitch 的 IPRoyal 会话上使用 cf_clearance

IPRoyalClearance 维护一个粘性会话及其 cookie;killswitch 触发或 Cloudflare 再次挑战时同时更新两者,否则一直复用相同的 IP、cookie 和 User-Agent。secrets.token_hex(4) 正好生成 IPRoyal 要求的 8 个字符。

iproyal_nslsolver.py
# iproyal_nslsolver.py  (pip install curl_cffi)
import secrets
from curl_cffi import requests

NSL_API_KEY = "nsl_YOUR_API_KEY"
IPROYAL_USERNAME = "YOUR_IPROYAL_USERNAME"
IPROYAL_PASSWORD = "YOUR_IPROYAL_PASSWORD"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
      "(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36")


def iproyal_proxy(country="gb", session=None, lifetime="30m", killswitch=True):
    """IPRoyal residential: every option is appended to the PASSWORD with
    underscores. _session- must be exactly 8 alphanumeric characters; without
    it, each request gets a new IP."""
    password = f"{IPROYAL_PASSWORD}_country-{country}"
    if session:
        password += f"_session-{session}_lifetime-{lifetime}"  # one unit: 30m, 2h...
        if killswitch:
            password += "_killswitch-1"  # 410 instead of a silent IP swap
    return f"http://{IPROYAL_USERNAME}:{password}@geo.iproyal.com:12321"


def solve(payload):
    r = requests.post("https://api.nslsolver.com/solve",
                      headers={"X-API-Key": NSL_API_KEY}, json=payload, timeout=180)
    data = r.json()
    if r.status_code != 200 or not data.get("success"):
        raise RuntimeError(f"NSLSolver {r.status_code}: {data.get('error', data)}")
    return data


def browser_session(proxy, user_agent, accept_language=None, impersonate="chrome"):
    # TLS fingerprint must match the UA: "chrome" for a Chrome UA, "safari_ios"
    # for the iPhone Safari UA that a Challenge solve returns
    s = requests.Session(impersonate=impersonate)
    s.proxies = {"http": proxy, "https": proxy}
    s.headers["User-Agent"] = user_agent
    if accept_language:
        s.headers["Accept-Language"] = accept_language
    return s


def is_challenge(resp):
    return resp.headers.get("cf-mitigated") == "challenge" or (
        resp.status_code in (403, 503) and "Just a moment..." in resp.text[:5000])


class IPRoyalClearance:
    """One sticky IPRoyal session and the cf_clearance earned on it. With
    _killswitch-1 a lost IP surfaces as an error (HTTP 410, reported by curl as
    a failed CONNECT for https URLs), so we renew instead of sending a cookie
    from an IP that never earned it."""

    def __init__(self, url, site_key, country="gb", lang="en-GB,en;q=0.9"):
        self.url, self.site_key, self.country, self.lang = url, site_key, country, lang
        self.renew()

    def renew(self):
        self.proxy = iproyal_proxy(self.country, session=secrets.token_hex(4))  # 8 chars
        cf = solve({"type": "challenge", "url": self.url, "site_key": self.site_key,
                    "proxy": self.proxy, "accept_language": self.lang})
        self.s = browser_session(self.proxy, cf["user_agent"], self.lang, impersonate="safari_ios")
        for name, value in cf["cookies"].items():  # cf_clearance
            self.s.cookies.set(name, value)

    def get(self, url):
        try:
            r = self.s.get(url)
        except Exception as exc:
            if "410" not in str(exc):
                raise
            self.renew()  # the sticky IP is gone: new session, new solve
            return self.s.get(url)
        if is_challenge(r):  # cookie expired or rejected
            self.renew()
            r = self.s.get(url)
        return r


cf = IPRoyalClearance("https://cf-protected.example.com/", "0x4AAAAAAA...")
for page in range(1, 6):
    print(page, cf.get(f"https://cf-protected.example.com/catalog?page={page}").status_code)

Python:通过 IPRoyal 获取 Kasada x-kpsdk 请求头

Kasada 调用很短,这里用 10 分钟的 lifetime 就够了。从浏览器 Network 面板获取 p_js_path、fp_host 和 tl_host,并通过同一会话、用同一 User-Agent 发送返回的请求头。

iproyal_nslsolver.py
# Same file: Kasada headers on an 8-character IPRoyal session.
kasada_proxy = iproyal_proxy("gb", session=secrets.token_hex(4), lifetime="10m")

k = solve({
    "type": "kasada",
    "url": "https://www.kasada-site.example.com/login",
    "user_agent": UA,
    "ua_version": 145,
    "kasada_config": {
        "p_js_path": "/<uuid-1>/<uuid-2>/p.js",       # the target's real p.js path (DevTools > Network)
        "fp_host": "www.kasada-site.example.com",     # host serving /fp
        "tl_host": "api.kasada-site.example.com",     # host receiving POST /tl
    },
    "proxy": kasada_proxy,
})

api = browser_session(kasada_proxy, UA)
r = api.post("https://api.kasada-site.example.com/v1/search",
             headers=k["headers"], json={"q": "..."})
print(r.status_code)  # x-kpsdk-cd is single-use: solve again for the next call

Python:通过 IPRoyal 获取 Akamai _abck cookie

本示例加入 _city-london 演示城市定位。用同一 User-Agent 回放返回的全部 cookie,而不只是 _abck。Akamai 在 NSLSolver 上处于测试阶段。

iproyal_nslsolver.py
# Same file: Akamai cookies on a city-targeted IPRoyal session.
def iproyal_city_proxy(country, city, session, lifetime="30m"):
    password = (f"{IPROYAL_PASSWORD}_country-{country}_city-{city}"
                f"_session-{session}_lifetime-{lifetime}_killswitch-1")
    return f"http://{IPROYAL_USERNAME}:{password}@geo.iproyal.com:12321"


akamai_proxy = iproyal_city_proxy("gb", "london", secrets.token_hex(4))

ak = solve({
    "type": "akamai",
    "url": "https://akamai-site.example.com/login",
    "user_agent": UA,
    "proxy": akamai_proxy,  # required for akamai
})

shop = browser_session(akamai_proxy, UA, "en-GB,en;q=0.9")
for name, value in ak["cookies"].items():  # _abck, bm_sz, ...
    shop.cookies.set(name, value)
r = shop.get("https://akamai-site.example.com/api/products")
print(r.status_code)  # 403 "Access Denied" = solve again

Node.js:用 undici 实现同样的流程

由于选项写在密码中,放入 URL 前请先用 encodeURIComponent 编码。undici 的 ProxyAgent 会解码凭据并发送给网关。

iproyal-nslsolver.mjs
// iproyal-nslsolver.mjs  (Node 18+, npm i undici)
import { randomBytes } from "node:crypto";
import { fetch, ProxyAgent } from "undici";

const NSL_API_KEY = "nsl_YOUR_API_KEY";
const IPROYAL_USERNAME = "YOUR_IPROYAL_USERNAME";
const IPROYAL_PASSWORD = "YOUR_IPROYAL_PASSWORD";
const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " +
  "(KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36";

// Options go in the PASSWORD. randomBytes(4) -> 8 hex characters, as IPRoyal requires.
function iproyalProxy({ country = "gb", lifetime = "30m" } = {}) {
  const session = randomBytes(4).toString("hex");
  const password = IPROYAL_PASSWORD + "_country-" + country + "_session-" + session +
    "_lifetime-" + lifetime + "_killswitch-1";
  return "http://" + IPROYAL_USERNAME + ":" + encodeURIComponent(password) + "@geo.iproyal.com:12321";
}

async function solve(payload) {
  const res = await fetch("https://api.nslsolver.com/solve", {
    method: "POST",
    headers: { "X-API-Key": NSL_API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
  const data = await res.json();
  if (!res.ok || !data.success) {
    throw new Error("NSLSolver " + res.status + ": " + (data.error || JSON.stringify(data)));
  }
  return data;
}

const cookieHeader = (cookies) =>
  Object.entries(cookies).map(([k, v]) => k + "=" + v).join("; ");

// 1) Cloudflare Challenge from a UK sticky IP
const cfProxy = iproyalProxy({ country: "gb" });
const cf = await solve({
  type: "challenge",
  url: "https://cf-protected.example.com/",
  site_key: "0x4AAAAAAA...",
  proxy: cfProxy,
  accept_language: "en-GB,en;q=0.9",
});
const page = await fetch("https://cf-protected.example.com/catalog", {
  dispatcher: new ProxyAgent(cfProxy),
  headers: { "User-Agent": cf.user_agent, "Accept-Language": "en-GB,en;q=0.9", Cookie: cookieHeader(cf.cookies) },
});
console.log("challenge", page.status);
// With _killswitch-1, a lost sticky IP makes fetch() throw (proxy answered 410):
// catch it, build a new iproyalProxy() and solve again.

// 2) Kasada
const kProxy = iproyalProxy({ country: "gb", lifetime: "10m" });
const k = await solve({
  type: "kasada",
  url: "https://www.kasada-site.example.com/login",
  user_agent: UA,
  ua_version: 145,
  kasada_config: {
    p_js_path: "/<uuid-1>/<uuid-2>/p.js",     // the target's real p.js path (DevTools > Network)
    fp_host: "www.kasada-site.example.com",   // host serving /fp
    tl_host: "api.kasada-site.example.com",   // host receiving POST /tl
  },
  proxy: kProxy,
});
const api = await fetch("https://api.kasada-site.example.com/v1/search", {
  method: "POST",
  dispatcher: new ProxyAgent(kProxy),
  headers: { ...k.headers, "User-Agent": UA, "Content-Type": "application/json" },
  body: JSON.stringify({ q: "..." }),
});
console.log("kasada", api.status);

// 3) Akamai
const akProxy = iproyalProxy({ country: "gb" });
const ak = await solve({ type: "akamai", url: "https://akamai-site.example.com/login", user_agent: UA, proxy: akProxy });
const products = await fetch("https://akamai-site.example.com/api/products", {
  dispatcher: new ProxyAgent(akProxy),
  headers: { "User-Agent": UA, Cookie: cookieHeader(ak.cookies) },
});
console.log("akamai", products.status);
// Node's fetch does not copy Chrome's TLS fingerprint; if a strict site still
// blocks it, send the follow-up requests from Python with curl_cffi.

完整 NSLSolver API 文档

IPRoyal 配合 NSLSolver 的常见问题排查

NSLSolver 各状态码以及 Cloudflare、Kasada、Akamai 错误的含义,请参阅反爬虫错误代码速查。

现象常见原因解决方法
会话无法保持_session 的值不是恰好 8 位字母数字。用 secrets.token_hex(4) 或 randomBytes(4).toString("hex") 生成。
407 Proxy Authentication Required选项加在了用户名而不是密码上。用户名保持原样,把 _country-...、_session-... 追加到密码。
代理返回 HTTP 410设置了 _killswitch-1,且粘性 IP 已不可用。开启新会话并重新求解;旧 cookie 不能再用。
lifetime 不生效组合了两个单位,例如 1h30m。只用一个单位:90m。
NSLSolver 400 Validation failed代理缺少协议前缀,或缺少必填字段。发送完整的 http:// URL,并检查错误中指出的字段。
NSLSolver 503 Solve failed求解未完成,不计费。按退避策略重试;同一会话反复失败时开启新会话。

相关阅读

常见问题

如何把 IPRoyal 代理传给 NSLSolver?

把 http://USERNAME:PASSWORD_country-gb_session-a1b2c3d4_lifetime-30m@geo.iproyal.com:12321 作为 POST /solve 的 proxy 字段,然后让你自己的请求走完全相同的 URL。选项写在密码中,用户名保持不变。

为什么我的 IPRoyal 粘性会话总是换 IP?

最常见的原因是 _session 的值不是恰好 8 位字母数字,或者密码字符串在请求之间发生了变化。每个会话生成一个 8 位值,并复用完全相同的代理 URL。

_killswitch-1 有什么作用?

通常 IPRoyal 会悄悄替换不可用的粘性 IP。加上 _killswitch-1 后,代理会返回 HTTP 410,你的代码就知道 IP 已失效,可以在新会话上重新求解,而不是从错误的 IP 发送与 IP 绑定的 cookie。

用于 cf_clearance 的 IPRoyal lifetime 应该设多长?

至少与 cookie 的复用时间一样长。Cloudflare 默认的 Challenge Passage 是 30 分钟,所以 _lifetime-30m 是个不错的起点;IPRoyal 允许 1 秒至 7 天。

配合 IPRoyal 代理使用 NSLSolver 的费用是多少?

NSLSolver 按成功求解计费:Cloudflare Challenge 每 1,000 次 $1.00,Kasada $1.50,Akamai(测试版)$2.00。失败的求解不计费。IPRoyal 按你的 IPRoyal 套餐单独收取代理流量费用。

把你的 IPRoyal 代理接入 NSLSolver

通过你自己的住宅 IP 获取 Kasada 请求头、Akamai cookie 和 cf_clearance,全部在服务端求解,不使用浏览器。只对成功的求解计费,使用 Google、Gmail 或 Proton 注册即可获得免费额度。