158人参与 • 2024-09-23 • 软件测试
点击方法在web自动化测试中经常用到,下面就来介绍一下selenium常用和不常用的点击方法;
这是最简单和最常用的方法。通过选中要点击的元素,然后使用 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()
有时候使用 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)
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 类来解决。
#!/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点击元素方法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论