Selenium处理弹窗、警报和验证码识别

在 Web 自动化测试或爬虫开发中,Selenium 是最常用的工具之一,但页面中的弹窗、系统警报和验证码往往是自动化流程中的 "拦路虎"。本文将系统讲解 Selenium 处理各类弹窗、警报的核心方法,并结合实际场景介绍验证码识别的常用解决方案,帮助开发者突破这些自动化难点。

一、Selenium 处理系统警报(Alert)

Web 页面中的系统警报(JavaScript Alert)是最基础的弹窗类型,通常由alert()confirm()prompt()三种方法触发,这类弹窗不属于页面 DOM 元素,无法通过常规的元素定位方式操作,必须使用 Selenium 的switch_to.alert接口处理。

1. 核心操作方法

Selenium 为 Alert 弹窗提供了统一的操作接口,核心方法如下:

方法 作用
switch_to.alert 切换到当前页面的警报弹窗
text 获取弹窗中的文本内容
accept() 点击 "确定" 按钮(关闭弹窗)
dismiss() 点击 "取消" 按钮(仅适用于 confirm/prompt 弹窗)
send_keys() 向 prompt 弹窗输入文本(仅适用于 prompt 弹窗)

2. 实战示例

(1)处理普通提示弹窗(Alert)

python

运行

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# 初始化浏览器
driver = webdriver.Chrome()
driver.get("https://www.example.com/alert-page")

# 触发弹窗
driver.find_element(By.ID, "alert-btn").click()
time.sleep(1)  # 等待弹窗加载

# 切换到弹窗并操作
alert = driver.switch_to.alert
print("弹窗文本:", alert.text)  # 打印弹窗内容
alert.accept()  # 点击确定关闭弹窗

# 关闭浏览器
driver.quit()
(2)处理确认弹窗(Confirm)

python

运行

复制代码
# 触发确认弹窗
driver.find_element(By.ID, "confirm-btn").click()
time.sleep(1)

# 切换到弹窗
confirm_alert = driver.switch_to.alert
print("确认弹窗文本:", confirm_alert.text)
# 选择取消(若选择确定则用accept())
confirm_alert.dismiss()
(3)处理输入弹窗(Prompt)

python

运行

复制代码
# 触发输入弹窗
driver.find_element(By.ID, "prompt-btn").click()
time.sleep(1)

# 切换到弹窗并输入内容
prompt_alert = driver.switch_to.alert
prompt_alert.send_keys("自动化测试输入内容")  # 输入文本
prompt_alert.accept()  # 确认输入

3. 异常处理

若页面无弹窗时调用switch_to.alert会抛出NoAlertPresentException,建议增加异常捕获:

python

运行

复制代码
from selenium.common.exceptions import NoAlertPresentException

try:
    alert = driver.switch_to.alert
    alert.accept()
except NoAlertPresentException:
    print("当前页面无警报弹窗")

二、Selenium 处理页面弹窗(Modal)

页面弹窗(如登录弹窗、提示框)属于 DOM 元素,本质是普通网页元素,可通过常规的元素定位方法操作,核心思路是:先定位弹窗元素,再操作弹窗内的按钮 / 输入框,最后关闭弹窗。

1. 实战示例(处理登录弹窗)

python

运行

复制代码
# 定位弹窗中的用户名输入框
username_input = driver.find_element(By.ID, "modal-username")
username_input.send_keys("test_user")

# 定位密码输入框
password_input = driver.find_element(By.ID, "modal-password")
password_input.send_keys("test_pass")

# 点击登录按钮
login_btn = driver.find_element(By.ID, "modal-login-btn")
login_btn.click()

# 关闭弹窗(若登录后需关闭)
close_btn = driver.find_element(By.CLASS_NAME, "modal-close")
close_btn.click()

2. 关键注意事项

  • 页面弹窗可能存在加载延迟 ,建议使用WebDriverWait等待元素可点击,避免元素未加载完成导致操作失败:

    python

    运行

    复制代码
    from selenium.webdriver.support.wait import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    # 等待弹窗关闭按钮加载完成(最长等待10秒)
    close_btn = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "modal-close"))
    )
    close_btn.click()
  • 部分弹窗通过z-index层级控制显示,需确保定位的是当前可见的弹窗元素。

三、Selenium 处理验证码识别

验证码是网站用于区分人机操作的核心手段,常见类型有:图片验证码、滑块验证码、短信验证码、点选验证码等。Selenium 本身无法直接识别验证码,需结合第三方工具或接口实现。

1. 图片验证码(最基础类型)

(1)核心思路
  1. 截取验证码图片并保存到本地;
  2. 调用验证码识别接口 / 本地识别库解析验证码;
  3. 将识别结果输入到验证码输入框。
(2)实战示例(结合 ddddocr 识别图片验证码)

ddddocr是开源的 Python 验证码识别库,支持常见的数字、字母组合验证码识别,需先安装:

bash

运行

复制代码
pip install ddddocr selenium pillow

核心代码:

python

运行

复制代码
from selenium import webdriver
from selenium.webdriver.common.by import By
from PIL import Image
import ddddocr
import time

# 初始化浏览器
driver = webdriver.Chrome()
driver.get("https://www.example.com/captcha-page")
time.sleep(2)

# 1. 截取验证码图片
captcha_element = driver.find_element(By.ID, "captcha-img")  # 定位验证码图片元素
# 获取图片位置和尺寸
location = captcha_element.location
size = captcha_element.size
# 截取整个页面并裁剪出验证码区域
driver.save_screenshot("full_page.png")
img = Image.open("full_page.png")
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
captcha_img = img.crop((left, top, right, bottom))
captcha_img.save("captcha.png")

# 2. 调用ddddocr识别验证码
ocr = ddddocr.DdddOcr()
with open("captcha.png", "rb") as f:
    captcha_text = ocr.classification(f.read())
print("识别的验证码:", captcha_text)

# 3. 输入验证码
captcha_input = driver.find_element(By.ID, "captcha-input")
captcha_input.send_keys(captcha_text)

# 4. 提交表单
submit_btn = driver.find_element(By.ID, "submit-btn")
submit_btn.click()

driver.quit()

2. 滑块验证码(常见反爬类型)

滑块验证码需要模拟鼠标拖动滑块完成验证,Selenium 可通过ActionChains实现鼠标操作,核心思路:定位滑块元素→计算滑动距离→模拟拖动。

实战示例:

python

运行

复制代码
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

# 等待滑块元素加载
slider = WebDriverWait(driver, 10).until(
    EC.element_to_be_clickable((By.CLASS_NAME, "slider-btn"))
)
# 模拟拖动滑块(从左到右,滑动距离可根据实际场景调整)
action = ActionChains(driver)
action.click_and_hold(slider).move_by_offset(200, 0).release().perform()
time.sleep(2)  # 等待验证完成

3. 其他验证码解决方案

  • 短信验证码:可通过对接短信接收平台(如短信宝、接码平台)获取验证码,再输入到页面;
  • 点选验证码 :需结合图像识别(如 OpenCV)定位目标点,再通过ActionChains模拟点击;
  • 付费识别接口:对于复杂验证码(如异形字符、点选),可使用超级鹰、云打码等付费接口,识别率更高;
  • 绕过验证码:测试环境下,可协调开发人员提供 "免验证码" 开关,或使用测试账号跳过验证码验证(最优方案)。

四、注意事项与最佳实践

  1. 处理弹窗时,优先区分系统警报(Alert)页面弹窗(Modal) ,前者用switch_to.alert,后者用常规元素定位;
  2. 所有弹窗操作建议增加等待时间,避免页面加载延迟导致操作失败;
  3. 验证码识别优先选择测试环境绕过方案,生产环境需结合业务场景选择合适的识别方式,注意遵守网站规则;
  4. 滑块验证码拖动时,可模拟人类滑动轨迹(如先快后慢),避免匀速滑动被识别为机器操作。

总结

  1. Selenium 处理系统警报需使用switch_to.alert接口,支持accept()dismiss()send_keys()等核心操作;
  2. 页面弹窗本质是 DOM 元素,可通过常规元素定位 + 等待机制操作;
  3. 验证码识别无通用方案,图片验证码可使用ddddocr,滑块验证码用ActionChains模拟拖动,复杂场景建议使用付费接口或测试环境绕过。

掌握以上方法,可解决 Web 自动化中 90% 以上的弹窗、警报和验证码问题,大幅提升自动化流程的稳定性和成功率。

相关推荐
猿小羽2 小时前
[TEST] Selenium 自动化测试 - 1769134527168
selenium·测试工具
深蓝电商API2 小时前
Selenium模拟滚动加载无限下拉页面
爬虫·python·selenium
猿小羽2 小时前
[TEST] Selenium 自动化测试 - 1769138584825
selenium·测试工具
小王子10242 小时前
Redis Queue 安装与使用
redis·python·任务队列·rq·redis queue
人工智能AI技术2 小时前
【Agent从入门到实践】26 使用Chroma搭建本地向量库,实现Agent的短期记忆
人工智能·python
赤狐先生2 小时前
第三步--根据python基础语法完成一个简单的深度学习模拟
开发语言·python·深度学习
victory04312 小时前
pytorch函数使用规律-不必再死记硬背
人工智能·pytorch·python
rjc_lihui2 小时前
LightGBM 从入门到精通 (来自deepseek)
python
YUISOK2 小时前
如何使用uiautomator2+Weditor 可视化查看一个app组件的vm树
python·软件工程