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)
相关推荐
belldeep20 小时前
python:Selenium 4.47 编码新的写法
python·selenium
降临-max21 小时前
Postman断言、数据驱动+Jenkins集成
软件测试·测试工具·postman
IT小白杨1 天前
工程视角下的浏览器环境API:资源模型、权限审计与MCP实践
大数据·经验分享·selenium·chrome devtools·安全架构·指纹浏览器
随风而飘1861 天前
KEITHLEY吉时利 2400 数字源表
人工智能·功能测试·科技·测试工具
程序员三藏2 天前
自动化测试用例编写详解
自动化测试·软件测试·python·功能测试·测试工具·职场和发展·测试用例
测试老哥2 天前
Pytest自动化测试框架tep环境变量、fixtures、用例三者之间的关系
自动化测试·软件测试·python·测试工具·测试用例·pytest·职场发展
IT小白杨2 天前
当MCP遇上指纹浏览器:AI自然语言驱动隔离环境的实践思路
人工智能·经验分享·selenium·安全·业界资讯·指纹浏览器
qq_513728042 天前
Selenium 显式等待
selenium·测试工具
St_rive2 天前
selenium cookie的处理
数据库·selenium·测试工具