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

相关推荐
luoluoal10 小时前
基于python的小区监控图像拼接系统(源码+文档)
python·mysql·django·毕业设计·源码
BoBoZz1910 小时前
MotionBlur 演示简单运动模糊
python·vtk·图形渲染·图形处理
十八度的天空11 小时前
第01节 Python的基础语法
开发语言·python
BoBoZz1911 小时前
GradientBackground 比较不同类型的背景渐变着色模式与坐标转换
python·vtk·图形渲染·图形处理
540_54011 小时前
ADVANCE Day32
人工智能·python·机器学习
STLearner11 小时前
AAAI 2026 | 图基础模型(GFM)&文本属性图(TAG)高分论文
人工智能·python·深度学习·神经网络·机器学习·数据挖掘·图论
小北方城市网11 小时前
Python + 前后端全栈进阶课程(共 10 节|完整版递进式|从技术深化→项目落地→就业进阶,无缝衔接基础课)
大数据·开发语言·网络·python·数据库架构
nvd1111 小时前
故障排查:Pytest Asyncio Event Loop Closed 错误
python
deephub12 小时前
Lux 上手指南:让 AI 直接操作你的电脑
人工智能·python·大语言模型·agent
Channing Lewis12 小时前
Python读取excel转成html,并且复制excel中单元格的颜色(字体或填充)
python·html·excel