You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Selenium Stealth设置未同步至新标签页的问题排查与解决求助

Selenium-Stealth仅初始标签页生效的问题原因及解决方法

问题原因

selenium-stealth的隐身修改是标签页上下文级别的:它通过向当前活跃标签页的window对象注入JS代码,修改浏览器指纹特征(如navigator属性、WebGL信息等)来规避检测。但新打开的标签页会创建独立的浏览器上下文,不会继承之前的修改,因此仍会暴露Selenium的原始特征,被反机器人机制拦截。


解决方案1:切换新标签页后重新执行stealth配置

每次打开新标签页后,切换到该标签页并重新调用stealth()函数,让新标签页应用隐身设置。

修改后的完整代码:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium_stealth import stealth
import time

options = webdriver.ChromeOptions()
options.add_argument("--log-level=3")
options.add_argument("start-maximized")
options.add_argument("--mute-audio")
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
options.binary_location = r"C:\Program Files\Google\Chrome Beta\Application\chrome.exe"  # 转义反斜杠避免语法错误
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

bot = webdriver.Chrome(service=Service("chromedriver.exe"), options=options)

# 初始化第一个标签页的隐身配置
stealth(bot,
        languages=["en-US", "en"],
        vendor="Google Inc.",
        platform="Win32",
        webgl_vendor="Intel Inc.",
        renderer="Intel Iris OpenGL Engine",
        fix_hairline=True,
        )

bot.get("https://infosimples.github.io/detect-headless/")
time.sleep(5)

# 打开新标签页
bot.execute_script('window.open("https://infosimples.github.io/detect-headless/","_blank");')
time.sleep(1)

# 切换到新标签页(window_handles列表中索引1为新标签页,0是初始页)
bot.switch_to.window(bot.window_handles[1])

# 对新标签页应用隐身配置
stealth(bot,
        languages=["en-US", "en"],
        vendor="Google Inc.",
        platform="Win32",
        webgl_vendor="Intel Inc.",
        renderer="Intel Iris OpenGL Engine",
        fix_hairline=True,
        )

time.sleep(20)
bot.quit()

解决方案2:通过CDP全局注入隐身脚本(更高效)

利用Chrome DevTools Protocol (CDP) 的Page.addScriptToEvaluateOnNewDocument命令,将隐身脚本设置为所有新页面加载前自动执行。这种方法无需为每个新标签页重复调用stealth(),适合多标签页场景。

完整代码示例:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium_stealth import stealth
import time

options = webdriver.ChromeOptions()
options.add_argument("--log-level=3")
options.add_argument("start-maximized")
options.add_argument("--mute-audio")
options.add_argument('--ignore-ssl-errors=yes')
options.add_argument('--ignore-certificate-errors')
options.binary_location = r"C:\Program Files\Google\Chrome Beta\Application\chrome.exe"
options.add_experimental_option("excludeSwitches", ["enable-automation"])
options.add_experimental_option('useAutomationExtension', False)

bot = webdriver.Chrome(service=Service("chromedriver.exe"), options=options)

# 全局注入隐身脚本,所有新打开的页面都会自动执行
bot.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
    "source": '''
        // 模拟真实浏览器的navigator属性
        Object.defineProperty(navigator, 'webdriver', {get: () => undefined});
        Object.defineProperty(navigator, 'vendor', {get: () => 'Google Inc.'});
        Object.defineProperty(navigator, 'platform', {get: () => 'Win32'});
        Object.defineProperty(navigator, 'languages', {get: () => ['en-US', 'en']});
        
        // 修改WebGL指纹
        const originalGetContext = HTMLCanvasElement.prototype.getContext;
        HTMLCanvasElement.prototype.getContext = function(type) {
            const context = originalGetContext.call(this, type);
            if (type === 'webgl' || type === 'experimental-webgl') {
                const debugExt = context.getExtension('WEBGL_debug_renderer_info');
                Object.defineProperty(debugExt, 'UNMASKED_VENDOR_WEBGL', {get: () => 'Intel Inc.'});
                Object.defineProperty(debugExt, 'UNMASKED_RENDERER_WEBGL', {get: () => 'Intel Iris OpenGL Engine'});
            }
            return context;
        };
        
        // 修复hairline样式
        const originalGetComputedStyle = window.getComputedStyle;
        window.getComputedStyle = function(element) {
            const style = originalGetComputedStyle.call(this, element);
            if (style.getPropertyValue('border-top-width') === '1px') {
                style.setProperty('border-top-width', '0.5px');
            }
            return style;
        };
    '''
})

# 初始标签页也可调用stealth确保配置完全一致(可选)
stealth(bot,
        languages=["en-US", "en"],
        vendor="Google Inc.",
        platform="Win32",
        webgl_vendor="Intel Inc.",
        renderer="Intel Iris OpenGL Engine",
        fix_hairline=True,
        )

bot.get("https://infosimples.github.io/detect-headless/")
time.sleep(5)

# 打开新标签页,无需额外操作即可自动应用隐身配置
bot.execute_script('window.open("https://infosimples.github.io/detect-headless/","_blank");')
time.sleep(20)
bot.quit()

说明:上述脚本提取了selenium-stealth的核心修改逻辑,确保和原stealth()配置一致。你也可以查看selenium-stealth的源码,直接复用它生成的注入脚本,保证特征完全匹配。


内容的提问来源于stack exchange,提问作者Zen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 12:10:54