1. Selenium自动化测试函数深度解析
作为Web自动化测试领域的黄金标准工具,Selenium的函数库在实际项目中发挥着中枢神经作用。在上一期我们探讨了基础定位和页面操作函数后,这次将重点剖析那些容易被忽视却至关重要的函数方法。以Python语言为例,结合Edge浏览器的最新特性,我将分享在电商平台自动化测试中积累的实战经验。
注意:本文所有代码示例基于Selenium 4.8+和Edge 108+版本,部分函数在旧版本可能不兼容
1.1 函数分类与调用逻辑
Selenium的函数体系可分为三大类:
- 驱动控制函数:管理浏览器生命周期(如
quit()、close()) - 元素定位函数:支持XPath、CSS等8种定位方式(如
find_element()系列) - 交互操作函数:模拟用户行为(如
click()、send_keys())
# 典型函数调用链示例 driver = webdriver.Edge() driver.get("https://example.com") # 驱动控制 search_box = driver.find_element(By.NAME, "q") # 元素定位 search_box.send_keys("selenium" + Keys.RETURN) # 交互操作1.2 新版Edge的扩展管理函数
针对热词中"python selenium要在edge启用一个扩展程序"的需求,微软Edge提供了专属函数:
from selenium.webdriver.edge.options import Options options = Options() options.add_extension('path/to/extension.crx') # 加载本地扩展 options.use_chromium = True # 必须启用Chromium内核踩坑记录:Edge扩展安装后需要手动处理权限弹窗,建议添加
options.add_argument('--disable-extensions-file-access-check')
2. 核心交互函数进阶用法
2.1 输入操作函数优化
send_keys()函数存在三个高阶用法:
- 组合键操作:通过
Keys类实现快捷键from selenium.webdriver.common.keys import Keys element.send_keys(Keys.CONTROL + 'a') # 全选 - 文件上传:直接发送文件路径
upload = driver.find_element(By.XPATH, "//input[@type='file']") upload.send_keys("/Users/test/example.png") # 绝对路径 - 输入延迟模拟:人性化输入节奏
from time import sleep for char in "selenium": search_box.send_keys(char) sleep(0.3) # 300ms间隔
2.2 鼠标动作链函数
ActionChains类提供的函数能实现复杂交互:
from selenium.webdriver.common.action_chains import ActionChains actions = ActionChains(driver) actions.move_to_element(menu).pause(1).click(hidden_submenu).perform()典型应用场景:
- 三级级联菜单操作
- 拖拽滑块验证码
- 画布绘图操作
实战技巧:
pause()参数单位是秒,建议复杂操作间添加0.5-1秒间隔
3. 等待机制函数详解
3.1 显式等待函数组合
WebDriverWait配合expected_conditions的黄金组合:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10, poll_frequency=0.5) element = wait.until( EC.visibility_of_element_located((By.ID, "dynamic-element")) )常用条件判断函数:
| 函数名 | 作用描述 |
|---|---|
presence_of_element_located | 元素存在于DOM |
element_to_be_clickable | 元素可点击状态 |
text_to_be_present_in_element | 元素包含特定文本 |
3.2 自定义等待函数
通过lambda实现复杂等待条件:
wait.until(lambda d: len(d.find_elements(By.CLASS_NAME, "item")) >= 5)这种写法特别适合:
- 异步加载内容检查
- 分页数据加载等待
- 动态表格行数验证
4. JavaScript执行函数进阶
4.1 execute_script深度应用
driver.execute_script(""" let element = arguments[0]; element.style.border = '3px solid red'; return element.getBoundingClientRect(); """, target_element)典型使用场景:
- 修改元素样式(调试定位)
- 获取DOM属性(如滚动位置)
- 执行原生JS事件
4.2 异步脚本处理
Edge新版支持execute_async_script:
script = """ let callback = arguments[arguments.length - 1]; fetch('https://api.example.com').then(res => callback(res.json())); """ result = driver.execute_async_script(script)5. 特殊场景函数解决方案
5.1 文件下载函数重载
Edge需特殊配置下载路径:
params = { "behavior": "allow", "downloadPath": "/path/to/downloads" } driver.execute_cdp_cmd("Page.setDownloadBehavior", params)5.2 弹窗处理函数
# 获取弹窗文本 alert = driver.switch_to.alert print(alert.text) # 处理认证弹窗 driver.get("https://username:password@example.com")6. 性能优化函数组
6.1 页面加载策略控制
from selenium.webdriver.edge.options import Options options = Options() options.page_load_strategy = "eager" # 可选normal/eager/none三种模式对比:
normal:等待全部资源加载(默认)eager:DOM完成即继续(提升速度)none:不等待(适合SPA应用)
6.2 网络请求拦截
通过DevTools函数实现:
driver.execute_cdp_cmd("Network.enable", {}) driver.execute_cdp_cmd( "Network.setBlockedURLs", {"urls": ["*.adservice.com"]} )7. 函数调试与异常处理
7.1 元素状态检查函数
def is_element_present(driver, locator): try: driver.find_element(*locator) return True except NoSuchElementException: return False7.2 智能重试机制
from tenacity import retry, stop_after_attempt @retry(stop=stop_after_attempt(3)) def safe_click(element): try: element.click() except StaleElementReferenceException: element = relocate_element() raise8. 函数最佳实践总结
- 命名规范:采用
动作_对象格式,如click_submit_button() - 参数设计:必选参数在前,可选参数在后,带默认值
- 异常处理:明确捕获
NoSuchElementException等特定异常 - 日志记录:关键步骤添加
logging.info()输出 - 性能统计:用
time.perf_counter()记录关键操作耗时
最后分享一个真实案例:在某金融系统测试中,通过重写find_element()函数增加自动截图功能,使元素定位失败时的排查效率提升70%。这提醒我们,合理封装基础函数能显著提升框架的健壮性。