Selenium常用方法

一、安装驱动管理

如果通过安装驱动的方式来启动浏览器,每次浏览器更新后对应的驱动也需要更新,为了解决这个问题,selenium中提供了驱动管理工具webdriver-manager,有了webdriver-manager无需手动安装浏览器驱动,即使浏览器更新也不会影响自动化的执行。

selenium+驱动+浏览器的工作原理如下:

二、元素的定位

主要是cssSelector和xpath,打开浏览器开发者模式右键选择即可

三、操作测试对象

click():点击

send_key(""):模拟按键输入

clear():清除文本内容

text:获取文本信息

title:获取当前页面的标题

current_url:获取当前页面的url

四、窗口

driver.current_window_handle:获取当前页面的句柄

driver.window_handles:获取所有的页面的句柄

切换当前句柄为最新页面:

复制代码
curWindow = driver.current_window_handle
allWindows = driver.window_handles
    for window in allWindows:
       if window != curWindow:
            driver.switch_to.window(window)

driver.maximize_window():窗口最大化

driver.minimize_window():窗口最小化

driver.fullscreen_window():窗口全屏

driver.set_window_size(value,value):手动设置

save_screenshot("存放的路径"):截图

复制代码
filename = "autotest-"+datetime.datetime.now().strftime('%Y-%m-%d-%H%M%S')+'.png'
driver.save_screenshot('../images/'+filename)

close():关闭窗口

五、弹窗

alert=driver.switchTo.alert

alert.accept():确认

alert.dismiss():取消

alert=driver.switchTo.alert

alert.send_keys("hello")

alert.accept()

alert.dismiss()

六、等待

time.sleep():强制等待

implicitly_wait():隐式等待

显示等待

复制代码
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver,2)
wait.until(EC.invisibility_of_element((By.XPATH,'//[@id="2"]/div/div/div[3]/div[1]/div[1]/div')))

七、浏览器

1、浏览器导航

back():后退

forward():前进

refresh():刷新

2、浏览器参数设置

无头模式

复制代码
options = webdriver.ChromeOptions()
options.add_argument("-headless")
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()),options
=options)

页面加载策略

normal:默认值,等待所有资源下载

eager:DOM访问已准备就绪,但是诸如图像的其他资源可能仍在加载

none:不会阻塞webdriver

python 复制代码
options = webdriver.ChromeOptions()
options.page_load_strategy = 'eager'
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()),options
=options)
相关推荐
Hy行者勇哥1 天前
软件测试完整体系
测试工具
TunerT_TQ1 天前
Valhalla 静态工程审阅 #012|Hertz 源码证据驱动评测【大厂开源基础设施特辑】
测试工具·微服务·开源·github·字节跳动·cloudwego·http框架
Dr.kangder1 天前
嵌入式软件接口测试:从理论到实践的全面指南
测试工具·架构·嵌入式·测试覆盖率
冷凝娇2 天前
【Postman】2026总结
测试工具·postman
天才测试猿2 天前
实例介绍:Unittest框架及自动化测试实现流程
自动化测试·软件测试·python·selenium·测试工具·职场和发展·测试用例
TunerT_TQ2 天前
Valhalla 静态工程审阅 #009|Continue 源码证据驱动评测【大厂开源基础设施特辑】
vscode·测试工具·开源·llm·github·jetbrains·ai编程助手
Luminbox紫创测控3 天前
AM0太阳模拟器如何精准模拟太空环境:提升地面测试精度
测试工具·安全性测试·测试标准
我的xiaodoujiao3 天前
快速学习Python基础知识详细图文教程14--模块
开发语言·python·学习·测试工具
东舟技术3 天前
AI全链路测试智能体上线啦!
人工智能·功能测试·测试工具·自动化
Tinyfacture3 天前
接口自动化之添加商品(pytest)
python·测试工具·自动化·pytest