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

相关推荐
电院工程师37 分钟前
SIMON64/128算法Verilog流水线实现(附Python实现)
python·嵌入式硬件·算法·密码学
Python图像识别2 小时前
75_基于深度学习的咖啡叶片病害检测系统(yolo11、yolov8、yolov5+UI界面+Python项目源码+模型+标注好的数据集)
python·深度学习·yolo
闲人编程2 小时前
Python游戏开发入门:Pygame实战
开发语言·python·游戏·pygame·毕设·codecapsule
西游音月2 小时前
(2)pytest+Selenium自动化测试-环境准备
selenium·测试工具·pytest
雍凉明月夜3 小时前
人工智能学习中深度学习之python基础之 类
python·学习
Geo_V3 小时前
OpenAI 大模型 API 使用示例
python·chatgpt·openai·大模型应用·llm 开发
Hello_WOAIAI3 小时前
2.4 python装饰器在 Web 框架和测试中的实战应用
开发语言·前端·python
百锦再4 小时前
第1章 Rust语言概述
java·开发语言·人工智能·python·rust·go·1024程序员节
tokepson4 小时前
chatgpt-to-md优化并重新复习
python·ai·技术·pypi·记录
Victory_orsh4 小时前
“自然搞懂”深度学习(基于Pytorch架构)——010203
人工智能·pytorch·python·深度学习·神经网络·算法·机器学习