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)
相关推荐
猿小路17 小时前
抓包工具-Wireshark
网络·测试工具·wireshark
智航GIS18 小时前
10.4 Selenium:Web 自动化测试框架
前端·python·selenium·测试工具
廖圣平20 小时前
从零开始,福袋直播间脚本研究【三】《多进程执行selenium》
python·selenium·测试工具
合兴软件@1 天前
芯片适配快讯:合兴软件ISDT成功适配英飞凌TC3/TC4系列MCU
测试工具·车载系统·嵌入式实时数据库
Wpa.wk1 天前
性能测试-初识性能测试基础(性能测试流程,计划等)
java·运维·经验分享·测试工具·性能测试
我想吃烤肉肉1 天前
Playwright中page.locator和Selenium中find_element区别
爬虫·python·测试工具·自动化
0思必得01 天前
[Web自动化] Selenium基础介绍
前端·python·selenium·自动化·web自动化
测试19981 天前
Web自动化测试入门
自动化测试·软件测试·python·功能测试·selenium·测试工具·测试用例
食咗未1 天前
Linux tcpdump工具的使用
linux·服务器·网络·驱动开发·tcp/ip·测试工具·tcpdump