WebDriverWait是selenium中的等待类,可以设定一个等待条件,帮助我们等待页面加载完毕或某个元素出现以及消失。本文将从多个方面对其使用方法和实例进行详细阐述。
一、等待条件
WebDriverWait的等待条件可以有多种,其中比较常用的有以下几种:
- presence_of_element_located:元素是否在DOM中存在
- visibility_of_element_located:元素是否可见
- element_to_be_clickable:元素是否可以被点击
- text_to_be_present_in_element:元素中是否包含文本
使用方法如下:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By wait = WebDriverWait(driver, 10) element = wait.until(EC.presence_of_element_located((By.XPATH, '//div[@class="content"]')))
二、等待时间和轮询间隔
我们可以通过timeout参数设置最长等待时间,如果等待超时仍未出现等待条件,将抛出TimeoutException异常。同时,我们也可以通过poll_frequency参数设置轮询间隔,以避免等待时间过长影响效率。
示例代码:
from selenium.common.exceptions import TimeoutException try: element = WebDriverWait(driver, 10, 0.5).until(EC.visibility_of_element_located((By.CLASS_NAME, 'example-class'))) except TimeoutException: print("等待元素超时,该元素未能出现")
三、等待多个元素
有时我们需要等待多个元素出现或消失,可以使用ExpectedConditions类中的presence_of_all_elements_located和invisibility_of_all_elements等等方法。
示例代码:
from selenium.webdriver.support.expected_conditions import presence_of_all_elements_located, invisibility_of_all_elements elements = WebDriverWait(driver, 10).until(presence_of_all_elements_located((By.XPATH, '//div[@class="example-class"]'))) is_not_visible = WebDriverWait(driver, 10).until(invisibility_of_all_elements((By.XPATH, '//div[@class="example-class"]')))
四、等待frame切换和alert出现
在WebDriverWait中,我们也可以等待frame切换和alert弹窗出现。
示例代码:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) wait.until(EC.frame_to_be_available_and_switch_to_it('iframe_name')) alert = wait.until(EC.alert_is_present()) alert.accept()
五、等待自定义条件
在某些情况下,我们可能需要等待一些自定义的条件。我们可以通过编写自定义类来实现,只要实现了__call__方法并返回True或False即可。
示例代码:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC class my_condition(object): def __init__(self): pass def __call__(self, driver): driver.find_element_by_id('example_id').click() return True wait = WebDriverWait(driver, 10) wait.until(my_condition())
通过以上5个方面的阐述,我们可以更好地理解和掌握WebDriverWait函数,并在selenium自动化测试中使用它来提高测试效率。
原创文章,作者:小蓝,如若转载,请注明出处:https://www.506064.com/n/196263.html