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

相关推荐
阡陌..4 小时前
pytorch模型训练使用多GPU执行报错:Bus error (core dumped)(未解决)
人工智能·pytorch·python
0思必得04 小时前
[Web自动化] Selenium处理Cookie
前端·爬虫·python·selenium·自动化
喵手4 小时前
Python爬虫实战:房价/租金指数时间序列爬虫实战 - 从多页采集到趋势分析的完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·房价/租金指数时间序列·多页采集到趋势分析·采集结果sqlite到处
serve the people4 小时前
python环境搭建 (六) Makefile 简单使用方法
java·服务器·python
IT北辰4 小时前
基于Vue3+python+mysql8.0的财务凭证录入系统,前后端分离完整版(可赠送源码)
python·vue
墨染青竹梦悠然5 小时前
基于Django+vue的图书借阅管理系统
前端·vue.js·后端·python·django·毕业设计·毕设
多恩Stone5 小时前
【3DV 进阶-11】Trellis.2 数据处理与训练流程图
人工智能·pytorch·python·算法·3d·aigc·流程图
怪兽毕设5 小时前
基于Django的洗衣服务平台设计与实现
后端·python·django·洗衣服务平台
小小逐月者5 小时前
SQLModel 开发笔记:Python SQL 数据库操作的「简化神器」
数据库·笔记·python
曲幽5 小时前
FastAPI生命周期管理实战:从启动到关闭,如何优雅地管好你的“资源家当”
redis·python·fastapi·web·shutdown·startup·lifespan