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

如何使用Selenium处理创建账户后浏览器弹出的通知并点击

使用Selenium自动化点击浏览器创建账户通知

核心思路

浏览器通知属于浏览器层面的UI元素,而非网页DOM的一部分,通常需要通过配置浏览器权限+JavaScript执行的方式来定位并点击,不同浏览器的实现细节略有差异。


Chrome浏览器实现步骤

  1. 配置Chrome允许通知
    启动Chrome时需设置偏好,允许网站发送桌面通知,避免通知被拦截:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    chrome_options = Options()
    # 通过实验性选项配置通知权限
    chrome_options.add_experimental_option("prefs", {
        "profile.default_content_setting_values.notifications": 1  # 1=允许,2=禁止
    })
    
    driver = webdriver.Chrome(options=chrome_options)
    
  2. 等待通知出现并点击
    Chrome的通知嵌套在Shadow DOM中,需用JavaScript定位并触发点击:

    from selenium.webdriver.support.ui import WebDriverWait
    
    # 等待通知加载(最多等待10秒)
    WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("return document.querySelector('body > notification') !== null")
    )
    
    # 执行JS点击通知的确认按钮
    driver.execute_script("""
        const notification = document.querySelector('body > notification');
        notification.shadowRoot.querySelector('#action-button').click();
    """)
    

Firefox浏览器实现步骤

  1. 配置Firefox允许通知
    通过Firefox Profile设置通知权限:

    from selenium import webdriver
    from selenium.webdriver.firefox.options import Options
    
    firefox_options = Options()
    firefox_profile = webdriver.FirefoxProfile()
    # 启用桌面通知并设置允许权限
    firefox_profile.set_preference("dom.webnotifications.enabled", True)
    firefox_profile.set_preference("permissions.default.desktop-notification", 1)
    
    driver = webdriver.Firefox(firefox_profile=firefox_profile, options=firefox_options)
    
  2. 等待并点击通知
    Firefox的通知可直接通过DOM选择器定位:

    from selenium.webdriver.support.ui import WebDriverWait
    
    # 等待通知出现
    WebDriverWait(driver, 10).until(
        lambda d: d.execute_script("return document.querySelector('.notification-popup') !== null")
    )
    
    # 点击通知
    driver.execute_script("document.querySelector('.notification-popup').click();")
    

调试与注意事项

  • 确认通知DOM结构:右键点击通知选择「检查」,查看实际的元素选择器(不同浏览器/版本的通知DOM结构可能有差异)。
  • 延长等待时间:若通知出现延迟,可调整WebDriverWait的超时时间(比如改为15秒)。
  • 处理多通知场景:若页面可能弹出多个通知,需通过文本内容筛选目标通知,比如修改JS代码匹配“已创建”关键字:
    const notifications = document.querySelectorAll('body > notification');
    for (let n of notifications) {
        if (n.shadowRoot.textContent.includes('已创建')) {
            n.shadowRoot.querySelector('#action-button').click();
            break;
        }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 16:08:13