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 类来解决。

相关推荐
SCLchuck15 分钟前
人工智能-概率密度估计
人工智能·python·概率论·概率密度估计
摩拜芯城IC18 分钟前
PSD835G2-90UI 芯片参数资料意法半导体Flash PSD可编程系统微芯片
python·5g
清水白石0081 小时前
Python 缓存机制深度实战:从零打造带过期时间的记忆化装饰器
python·spring·缓存
Faker66363aaa1 小时前
中国传统园林建筑检测与识别---RetinaNet_PVT-M_FPN_1x_COCO原创
python
清水白石0082 小时前
NumPy 向量化实战指南:从原理到实践的性能革命
python·numpy
Coding茶水间2 小时前
基于深度学习的猪识别系统演示与介绍(YOLOv12/v11/v8/v5模型+Pyqt5界面+训练代码+数据集)
图像处理·人工智能·python·深度学习·yolo·目标检测
X54先生(人文科技)3 小时前
启蒙灯塔起源团预言—碳硅智能时代到来
人工智能·python·机器学习·语言模型
qq_24218863323 小时前
快速搭建跨环境检测服务的步骤
linux·开发语言·windows·python·macos
JaydenAI3 小时前
[拆解LangChain执行引擎]三种持久化模式的差异
python·langchain
老赵全栈实战3 小时前
《从零搭建RAG系统第4天:问题向量化+Milvus检索匹配+结果优化》
python·ai编程