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

相关推荐
量化吞吐机7 小时前
2026年下半年手工交易规则走向量化表达,产品该先接住哪一步
人工智能·python
Metaphor6928 小时前
使用 Python 读取和删除 Excel 文件属性
python·excel
迷迭香yy9 小时前
Python构建转融券多空识别系统从接口到因子的全流程 IG50免费开源股票数据API接口
开发语言·python·开源
月光船幽幽9 小时前
真实即粗糙,光滑是伪造
人工智能·python
一次旅行9 小时前
Attention机制从数学到工程:拆解缩放点积+多头注意力|附可运行PyTorch实现与踩坑指南
人工智能·pytorch·python
泡干脆面就番茄9 小时前
NumPy 科学计算完全指南:从数组创建到广播机制
python·numpy
denggun123459 小时前
信号量(DispatchSemaphore vs AsyncSemaphore)、swift协作式线程池 and python信号量
开发语言·python·swift
起光10 小时前
Python类与对象(一)
python
阿童木写作10 小时前
跨马翻译:AI批量图片翻译工具,视频字幕翻译与智能抠图一站式解决
大数据·人工智能·python·音视频
Zane199410 小时前
只改一个方向的引用,循环引用就能立刻被回收?一文讲透 weakref 弱引用
后端·python