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

如何在Python3+Selenium(PyCharm)中跳过、允许或阻止浏览器弹窗与提示框

处理Selenium中的浏览器弹窗与Alert提示框(Python3 + PyCharm)

Hey there! 我刚好在PyCharm里用Python3的Selenium折腾过各种弹窗,给你整理下实操的方法,分两类场景说:


一、浏览器权限类弹窗(通知、摄像头、地理位置等)

这类弹窗是浏览器本身触发的,不是页面的JS弹窗,没法用switch_to.alert处理,得在启动浏览器前提前配置权限,直接让浏览器自动允许/阻止,避免弹窗出现:

1. Chrome浏览器配置示例

用ChromeOptions设置权限参数,比如:

  • 允许/阻止通知权限
  • 允许/阻止摄像头权限
  • 跳过地理位置请求
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

# 初始化Chrome选项
chrome_options = Options()

# 配置权限:1=允许,2=阻止
chrome_options.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 1,  # 允许通知
    "profile.default_content_setting_values.media_stream_camera": 2,  # 阻止摄像头
    "profile.default_content_setting_values.geolocation": 1  # 允许地理位置
})

# 快速禁用所有通知的简化参数
# chrome_options.add_argument("--disable-notifications")

# 启动浏览器
driver = webdriver.Chrome(options=chrome_options)
driver.get("你的目标网址")

2. Firefox浏览器配置示例

用FirefoxProfile来设置权限:

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", False)
# 跳过摄像头权限询问(直接允许)
firefox_profile.set_preference("media.navigator.permission.disabled", True)

firefox_options.profile = firefox_profile
driver = webdriver.Firefox(options=firefox_options)

二、JavaScript提示框(Alert/Confirm/Prompt)

这类是页面JS弹出的提示框,Selenium提供了专门的switch_to.alert方法来控制:

1. 处理普通Alert(只有确定按钮)

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Chrome()
driver.get("包含Alert的页面")

# 等待Alert出现,最多等10秒(避免弹窗未加载直接调用报错)
alert = WebDriverWait(driver, 10).until(EC.alert_is_present())

# 查看Alert的文本内容
print("Alert提示内容:", alert.text)

# 点击确定按钮关闭Alert
alert.accept()

2. 处理Confirm提示框(确定/取消按钮)

# 等待Confirm弹窗加载完成
confirm_alert = WebDriverWait(driver, 10).until(EC.alert_is_present())

# 点击取消按钮
confirm_alert.dismiss()

# 要是需要点击确定,就用下面这行
# confirm_alert.accept()

3. 处理Prompt提示框(需要输入文本+确定/取消)

# 等待Prompt弹窗出现
prompt_alert = WebDriverWait(driver, 10).until(EC.alert_is_present())

# 在输入框中填写内容
prompt_alert.send_keys("这是我要输入的文本")

# 点击确定提交内容
prompt_alert.accept()

# 如果不想输入内容,直接取消弹窗
# prompt_alert.dismiss()

小提醒

  • 处理Alert时一定要等待弹窗出现,直接调用switch_to.alert可能会因为弹窗未加载而抛出异常,用WebDriverWait是最稳妥的方式。
  • 如果不确定页面会不会弹出Alert,可以加异常捕获避免报错:
try:
    alert = WebDriverWait(driver, 5).until(EC.alert_is_present())
    alert.accept()
except:
    print("页面未弹出Alert提示框")

内容的提问来源于stack exchange,提问作者Anel Čolak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:27:52