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

使用Undetected Chrome Driver在Python中打开新标签遇弹窗拦截问题

解决Undetected ChromeDriver中JavaScript打开新标签被拦截的问题

问题原因

浏览器默认会拦截非用户交互触发的脚本弹窗,直接调用window.open()属于主动触发行为,容易被判定为恶意操作,即使添加了--disable-popup-blocking参数也可能失效,尤其是在Undetected ChromeDriver的环境下,浏览器的安全机制会更严格。

解决方法

1. 强化弹窗拦截禁用配置

除了基础的--disable-popup-blocking,添加更多针对性的参数和偏好设置,确保Chrome彻底放开弹窗限制:

options = Options()
# 基础弹窗拦截禁用
options.add_argument('--disable-popup-blocking')
# 禁用隐私沙盒相关的弹窗限制特性
options.add_argument('--disable-features=PrivacySandboxSettings4,PopupsBlockedForUserTesting')
# 通过prefs设置允许弹窗
options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.popups": 0,
    "profile.content_settings.exceptions.automatic_downloads.*.setting": 1
})

2. 模拟真实用户交互触发新标签

改用创建<a>标签并模拟点击的方式,这种行为更接近真实用户操作,不容易被浏览器拦截:

chrome.get("https://www.google.com")
# 执行脚本创建a标签并模拟点击
chrome.execute_script("""
const link = document.createElement('a');
link.href = 'https://google.com';
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
""")

完整修正代码

import time
import undetected_chromedriver as uc
from selenium.webdriver.chrome.options import Options

options = Options()
options.add_argument('--disable-popup-blocking')
options.add_argument('--disable-features=PrivacySandboxSettings4,PopupsBlockedForUserTesting')
options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.popups": 0,
    "profile.content_settings.exceptions.automatic_downloads.*.setting": 1
})

if __name__ == '__main__':
    chrome = uc.Chrome(options=options)  
    time.sleep(1)
    chrome.get("https://www.google.com")
    # 模拟用户点击打开新标签
    chrome.execute_script("""
    const link = document.createElement('a');
    link.href = 'https://google.com';
    link.target = '_blank';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    """)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:39:21