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)
相关推荐
ysu_03142 天前
Postman接口调试实战指南-从HTTP请求到环境变量-Collection与自动化测试
网络·网络协议·测试工具·http·api·postman·可用性测试
ZhangJun953 天前
从零写一个类鲁大师的硬件检测小工具,软件附上,可直接使用
windows·测试工具·电脑·笔记本电脑·硬件架构
测试员周周4 天前
【jev应用到测试】94 条 UI 报错交给 Jev,三档判对 85.1%,开单闸门定在 0.6
人工智能·python·测试工具·单元测试·测试用例
xfilm埃利测量4 天前
从方阻到电阻率:四探针法如何把薄膜“测明白“
功能测试·测试工具·四探针·薄膜电阻测量
禹凕5 天前
机器学习之Selenium(Machina Learning about Selenium)
爬虫·python·selenium·测试工具·机器学习
水水不水啊7 天前
告别杂乱的调试窗口:我用 Python + WebView 写了一个现代化串口助手
python·测试工具·嵌入式·嵌入式开发·串口调试·串口助手
把头塞进显示器13 天前
电商平台-测试报告
python·selenium·pytest
霍格沃兹测试学院-小舟畅学14 天前
UI 测试的语义断言:Midscene aiAssert 比像素比对稳在哪、又会骗在哪
人工智能·测试工具
zuozewei14 天前
附录 A:主流工具对比选型表
人工智能·测试工具
我的xiaodoujiao14 天前
Django 基础知识详细图文教程 10-Django 模板引擎 3
后端·python·测试工具·django