显示等待进阶使用

一、显式等待原理

在代码中定义等待条件发生后在执行下一步代码
在最长等待时间内循环执行结束条件的函数

  • image
  • obj=WebDriverWait(dirver对象,最长等待时间,轮询时间)

  • image
  • obj.until(结束条件的函数对象)

二、expected_conditions

def test_wait_until(self):
      WebDriverWait(self.driver, 10).until(expected_conditions.element_to_be_clickable((By.CSS_SELECTOR, '#success_btn')))
      self.driver.find_element(By.CSS_SELECTOR, "#success_btn").click()
      time.sleep(3)

2.1、常见excepted_conditions

类型 示例函数 说明
element element_to_be_clickable() 元素是否可点击
element visibility_of_element_located() 元素是否可见
url url_contains() 针对URL
title title_is() 针对title
frame frame_to_be_avaible_and_swith_to_it(locator) 针对frame
alert alert_is_present() 针对alert

注意:要进入到expected_conditions的源码中确认函数返回的是否为WebElement对象

三、封装等待条件

  • 官方的excepted_conditions不可能覆盖所有的场景
  • 定制封装条件会更加灵活、可控
def element_can_more_click(target_element: tuple, next_element: tuple):
    """
    元素需要多次点击才出现预期效果
    :param target_element: 目标元素 (By.ID, "primary_btn")
    :param next_element: 目标元素的下一个元素 (By.XPATH, "/html/body/div[2]/div/div[1]/div/span")
    :return:
    """
    def _predicate(driver):
        """
        第一种情况,找到可以点击的按钮,则返回可点击的对象
        第二种情况,未找到,代码报错,但是异常会被until种的异常捕获逻辑捕获,然后继续循环
        """
        driver.find_element(*target_element).click()
        return driver.find_element(*next_element)
    return _predicate