Selenium点击元素的方法

前言

点击方法在web自动化测试中经常用到,下面就来介绍一下selenium常用和不常用的点击方法;

1、常用方法

1.1、使用 click() 方法:

这是最简单和最常用的方法。通过选中要点击的元素,然后使用 click() 方法来触发点击事件。

示例代码:

python 复制代码
element = self.driver.find_element(By.XPATH,"//div[@class='ant-select-selection__rendered']").find_elements(By.XPATH, "//div[@class='ant-select-selection-selected-value' and contains(@title,'全部')]")[1]

element.click()

1.2、使用 JavaScript 执行点击事件:

有时候使用 Selenium 的 click() 方法可能不够稳定,可以通过执行 JavaScript 代码来模拟点击事件。

示例代码:

python 复制代码
element = self.driver.find_element(By.XPATH,"//div[@class='ant-select-selection__rendered']").find_elements(By.XPATH, "//div[@class='ant-select-selection-selected-value' and contains(@title,'全部')]")[1]

self.driver.execute_script("arguments[0].click();", element)

1.3、使用 ActionChains 类:

ActionChains 类提供了模拟用户行为的方法,其中包括鼠标点击操作。

示例代码:

python 复制代码
element = self.driver.find_element(By.XPATH,"//div[@class='ant-select-selection__rendered']").find_elements(By.XPATH, "//div[@class='ant-select-selection-selected-value' and contains(@title,'全部')]")[1]

ActionChains(self.driver).click(element).perform()

这些方法可以根据具体情况和需求选择合适的方式来触发点击事件。通常情况下,推荐优先使用 click() 方法,如果出现稳定性问题,可以尝试使用 JavaScript 执行点击事件或者 ActionChains 类来解决。

相关推荐
狐凄21 分钟前
Python实例题:Python计算线性代数
开发语言·python·线性代数
西猫雷婶22 分钟前
pytorch基本运算-导数和f-string
人工智能·pytorch·python
述雾学java24 分钟前
深入理解 transforms.Normalize():PyTorch 图像预处理中的关键一步
人工智能·pytorch·python
要努力啊啊啊28 分钟前
使用 Python + SQLAlchemy 创建知识库数据库(SQLite)—— 构建本地知识库系统的基础《一》
数据库·人工智能·python·深度学习·自然语言处理·sqlite
Andrew_Xzw1 小时前
数据结构与算法(快速基础C++版)
开发语言·数据结构·c++·python·深度学习·算法
凤头百灵鸟2 小时前
Python语法基础篇(包含类型转换、拷贝、可变对象/不可变对象,函数,拆包,异常,模块,闭包,装饰器)
python
多多*3 小时前
LUA+Reids实现库存秒杀预扣减 记录流水 以及自己的思考
linux·开发语言·redis·python·bootstrap·lua
何双新4 小时前
第21讲、Odoo 18 配置机制详解
linux·python·开源
Wish3D4 小时前
阿里云OSS 上传文件 Python版本
开发语言·python·阿里云
阿福不是狗6 小时前
Python使用总结之Mac安装docker并配置wechaty
python·macos·docker