如何借助浏览器插件注入的 stealth.min.js 隐藏 WebDriver 属性?
解读
国内主流反爬团队普遍采用“WebDriver 指纹”作为第一道拦截策略,一旦检测到 navigator.webdriver=true 或 window.cdc_adoQpoasnfa76pfcZLmcfl_ 等特征,即触发 403、滑块或永封 IP。
Scrapy 原生并不渲染 JS,但借助 Scrapy-Splash 或 Scrapy-Playwright 中间件即可在本地拉起 Chromium,此时浏览器仍带有“自动化”标签。
stealth.min.js(Puppeteer-extra-stealth 的单文件版)通过 重写原型链、删除/替换 API、代理对象属性 三招,把 WebDriver 特征“抹平”,让浏览器指纹回到“正常用户”区间。
面试官真正想考察的是:
- 你是否知道 WebDriver 特征有哪些;
- 你是否能把 stealth 脚本注入到 Scrapy 渲染流程;
- 你是否理解注入顺序、缓存策略与版本锁定,避免升级后特征回潮。
知识点
-
WebDriver 暴露面
navigator.webdriver只读属性返回 true;window.cdc_adoQpoasnfa76pfcZLmcfl_等 Chromium 内部变量;navigator.plugins.length === 0、navigator.languages缺失;User-Agent带HeadlessChrome子串;window.outerHeight === 0、screen.colorDepth === 24等堆栈特征。
-
stealth.min.js 核心技巧
Object.defineProperty(navigator, 'webdriver', {get: () => undefined});- 删除
window.cdc_变量并冻结window描述符; - 伪造
plugins、mimeTypes、webgl渲染器字符串; - 通过
Proxy重写Function.prototype.toString,让检测方拿不到原生标记; - 在 所有 JS 上下文创建之前 提前执行,保证在反爬脚本之前“先入为主”。
-
Scrapy 渲染链注入点
- Scrapy-Splash:在
splash:go之前调用splash:autoload把 stealth.min.js 设为local://stealth.min.js,并开启splash.private_mode_enabled = false避免内存重置; - Scrapy-Playwright:重写
playwright_page_init_callback,在page.add_init_script(path="stealth.min.js")阶段注入,确保早于任何站点代码; - 若使用 Pyppeteer 中间件,可在
browser.newPage()后evaluateOnNewDocument注入; - 版本锁定:把 stealth.min.js 固定到项目
static/js/目录,禁止在线拉取,避免 CDN 污染或升级回滚。
- Scrapy-Splash:在
-
验证与回归
- 本地启动
http://localhost:8050/execute用 Splash 访问https://bot.sannysoft.com,确认 WebDriver=missing; - 在 Playwright 侧访问
https://hm.baidu.com/hm.js,抓包验证 无__driver_evaluate请求; - 每次升级 Chromium 主版本,重新跑一遍回归,防止新特征被漏掉。
- 本地启动
答案
以 Scrapy-Splash 为例,给出可直接落地的最小闭环:
- 把官方编译好的 stealth.min.js(约 65 kB)存到项目
myproject/static/js/stealth.min.js; - 在
settings.py关闭私有模式并提高缓存:SPLASH_PRIVATE_MODE = False SPLASH_COOKIES_DEBUG = True - 编写 Lua 脚本
stealth.lua:function main(splash, args) splash:autoload("local://stealth.min.js") splash:go(args.url) splash:wait(1) return splash:html() end - Spider 里调用:
yield SplashRequest(url, self.parse, endpoint='execute', args={'lua_source': self.stealth_lua}) - 部署到 Docker-Splash 国内镜像(
scrapinghub/splash:3.5-jumbo),并在docker-compose里把本地目录挂到/app/splash/static/js,保证local://协议能读到文件; - 线上验证:通过
https://bot.sannysoft.com检测,确认 WebDriver 属性已消失,且 navigator.plugins 返回 3 个伪造插件,即视为注入成功。
若采用 Scrapy-Playwright,则直接在中间件里:
async def init_page(page, request):
await page.add_init_script(path='myproject/static/js/stealth.min.js')
并设置 PLAYWRIGHT_BROWSER_TYPE = 'chromium' 与 PLAYWRIGHT_ARGS = ['--disable-blink-features=AutomationControlled'],即可达到同等效果。
拓展思考
- stealth 不是银弹:国内大厂已升级到 行为序列模型(鼠标轨迹、滚动速度、键盘间隔),仅靠隐藏 WebDriver 无法过掉滑块或 AI 风控,需要配合 轨迹伪造、请求间隔随机化、TLS 指纹定制(ja3/ja3n)等多层策略。
- stealth 脚本体积 与性能:在 Scrapy 高并发场景下,每页重复注入 65 kB 会拉高内存,可把脚本拆分为“核心特征” 10 kB 的 mini-stealth,并通过 Redis 缓存已注入标签页,减少重复计算。
- 合规红线:2022 年《反不正当竞争法》修订后,绕过“技术保护措施” 可被认定为侵权,务必在 客户授权 或 公开数据范围 内使用 stealth 技术,并在技术方案评审阶段同步法务,避免民事甚至刑事责任。