it编程 > 软件设计 > 软件测试

web自动化测试Selenium点击元素的常用方法

158人参与 2024-09-23 软件测试

前言

点击方法在web自动化测试中经常用到,下面就来介绍一下selenium常用和不常用的点击方法;

1、常用方法

1.1、使用 click() 方法:

这是最简单和最常用的方法。通过选中要点击的元素,然后使用 click() 方法来触发点击事件。
示例代码:

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 代码来模拟点击事件。
示例代码:

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 类提供了模拟用户行为的方法,其中包括鼠标点击操作。
示例代码:

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

附:selenium点击悬停元素

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from selenium.webdriver.common.action_chains import actionchains
from selenium import webdriver
from selenium.webdriver.support.wait import webdriverwait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by import by

driver = webdriver.chrome()
driver.get("http://www.baidu.com")
#找到设置
element = driver.find_element(by.id,'s-usersetting-top')
#鼠标悬停
actionchains(driver).move_to_element(element).perform()
#点击“高级搜索”
#webdriverwait(driver,10):在设置时间(10s)内,等待后面的条件发生。如果超过设置时间未发生,就抛出异常。等待元素出现:visibility_of_element_located
webdriverwait(driver,10).until(ec.visibility_of_element_located((by.xpath,'//*[@id="s-user-setting-menu"]/div/a[2]')))
driver.find_element_by_xpath('//*[@id="s-user-setting-menu"]/div/a[2]').click()

总结

到此这篇关于web自动化测试selenium点击元素常用方法的文章就介绍到这了,更多相关selenium点击元素方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

7900xt比7800xt性能强多少 7900xt和7800xt性能对比

09-20

谁才是最佳网游处理器? 锐龙5 9600X与酷睿i5-14600K游戏性能测试出炉

09-20

AMD 锐龙 9 9900X和7900X差距有多大? 两款处理器游戏性能测试出炉

09-12

RTX 4070 SUPER显卡极限性能如何? 七款4K游戏测试出炉

09-12

CPU性能对比为什么用1080P而不用4K模式? 1080p游戏测试

10-01

锐龙9600x怎么样 锐龙9600x游戏性能测试

10-01

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论