Selenium 4 中 visibility_of_element_located 用法详解 - Python 自动化测试
Selenium 4 中的 visibility_of_element_located 用法详解
在使用 Selenium 进行自动化测试时,经常需要等待页面元素加载完成后才能进行操作,否则会抛出 NoSuchElementException 异常。visibility_of_element_located 是 Selenium 4 提供的一个 Expected Condition(预期条件)方法,用于等待页面上的元素可见。
本文将详细介绍 visibility_of_element_located 的用法,并提供示例代码和常见问题解答,帮助你编写更健壮的自动化测试脚本。
使用方法
-
**导入必要的模块和类:**pythonfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.by import By
-
**创建 WebDriverWait 对象:**pythonwait = WebDriverWait(driver, 10) 其中: -
driver是你的 WebDriver 对象 (例如,webdriver.Chrome())。 -10是最长等待时间(以秒为单位),可以根据需要调整。 -
**使用
visibility_of_element_located方法等待元素可见:**pythonelement = wait.until(EC.visibility_of_element_located((By.ID, 'element_id'))) 其中: -By.ID指定元素定位方式为通过 ID,你也可以使用其他定位方式,例如By.XPATH,By.CSS_SELECTOR等。 -'element_id'是你要等待的元素的 ID 值,请根据实际情况修改。 -
**对返回的元素进行操作:**pythonelement.click()element.send_keys('text')
完整示例代码pythonfrom selenium import webdriverfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.by import By
创建 WebDriver 对象driver = webdriver.Chrome()
打开网页driver.get('https://www.example.com')
创建 WebDriverWait 对象wait = WebDriverWait(driver, 10)
使用 visibility_of_element_located 方法等待元素可见element = wait.until(EC.visibility_of_element_located((By.ID, 'element_id')))
对元素进行操作element.click()element.send_keys('text')
关闭浏览器driver.quit()
注意事项
visibility_of_element_located方法会检查元素是否在页面上可见并且占据一定的空间。如果元素隐藏 (例如,display: none或visibility: hidden),该方法会一直等待,直到元素可见。- 如果元素在页面上不存在,visibility_of_element_located方法会抛出TimeoutException异常。- 建议在使用visibility_of_element_located方法之前,先使用driver.get()方法加载页面,确保页面已经加载完成。
总结
visibility_of_element_located 是 Selenium 4 中一个非常实用的 Expected Condition 方法,可以帮助你编写更健壮、更可靠的自动化测试脚本。通过本文的介绍,相信你已经掌握了它的基本用法。在实际项目中,请根据具体情况选择合适的定位方式和等待时间。
原文地址: https://www.cveoy.top/t/topic/XGK 著作权归作者所有。请勿转载和采集!