expected_conditions 类提供了多种预定义的条件,这些条件可以用于 WebDriverWait 来等待页面上的某些特定状态或元素的状态。以下是 ExpectedConditions 中一些最常用的方法:
-
title_is(title)和title_contains(title)- 等待页面标题完全匹配给定的
title或包含指定的title。
- 等待页面标题完全匹配给定的
-
presence_of_element_located(locator)- 等待某个元素出现在DOM中,但不一定可见。这是查找元素前的一个好选择。
-
visibility_of_element_located(locator)- 等待某个元素不仅出现在DOM中而且是可见的(例如,它的宽度和高度都大于0)。
-
visibility_of(element)- 等待一个已经找到的元素变为可见。
-
element_to_be_clickable(locator)- 等待某个元素不仅是可见的,而且是可以点击的(即不是禁用状态)。这个条件非常适合用来确保按钮或其他交互式控件在用户操作之前处于可用状态。
-
invisibility_of_element_located(locator)和invisibility_of_element(element)- 等待某个元素从DOM中消失或者变得不可见。
-
text_to_be_present_in_element(locator, text_)- 等待指定的文本出现在由定位器找到的元素中。
-
text_to_be_present_in_element_value(locator, text_)- 等待指定的文本出现在由定位器找到的元素的value属性中。
-
frame_to_be_available_and_switch_to_it(locator)- 等待直到iframe可用并切换到它。
-
alert_is_present()- 等待直到出现JavaScript弹出框(如alert、confirm或prompt),并返回该警告对象。
-
element_selection_state_to_be(element, is_selected)- 等待元素的选择状态与期望的状态相匹配。
-
element_located_selection_state_to_be(locator, is_selected)- 等待位于指定位置的元素的选择状态与期望的状态相匹配。
使用这些条件可以帮助你编写更加稳定和可靠的自动化测试脚本,因为它们允许你在继续执行下一步操作之前确保页面达到了预期的状态。例如,在进行输入框输入之前等待其变得可见和可编辑,或者在点击按钮之前等待其变为可用。
下面是一个使用 ExpectedConditions 的例子:
from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 假设你已经创建了 WebDriver 的实例 driver wait = WebDriverWait(driver, 10) # 最大等待时间为10秒 # 等待直到登录按钮变得可点击,并点击它 login_button = wait.until(EC.element_to_be_clickable((By.ID, 'loginButton'))) login_button.click() # 等待直到欢迎消息出现并打印出来 welcome_message = wait.until(EC.presence_of_element_located((By.ID, 'welcomeMessage'))) print(welcome_message.text)

浙公网安备 33010602011771号