显式等待使用WebDriverWait类和expected_conditions模块
1.以下是expected_conditions模块中的一些API
-
title_is(title):
检查页面的标题是否正好等于期望的标题。
-
title_contains(substr):
检查页面的标题是否包含一个子串。
-
presence_of_element_located(locator):
检查是否在页面的DOM中至少有一个元素存在。
-
visibility_of_element_located(locator):
检查一个元素是否在页面中可见。元素的可见性不仅意味着元素非隐藏,而且元素的宽和高都大于0。
-
visibility_of(element):
检查元素是否可见。和visibility_of_element_located类似,但是参数是一个已经在DOM中的元素。
-
presence_of_all_elements_located(locator):
检查是否所有匹配的元素都存在于页面的DOM中。
-
text_to_be_present_in_element_value(locator, text):
检查元素的值是否包含期望的字串。
-
text_to_be_present_in_element(locator, text):
检查元素的文本是否包含期望的字串。
-
frame_to_be_available_and_switch_to_it(locator):
检查是否可以切换到指定的frame。
-
invisibility_of_element_located(locator):
检查元素是否处于不可见状态。
-
element_to_be_clickable(locator):
检查元素是否在页面中可见并且可以被点击。
-
staleness_of(element):
检查一个元素是否已经从DOM中移除。
-
element_to_be_selected(element):
检查元素是否被选中。
-
element_located_to_be_selected(locator):
检查一个元素是否可以被选中。
-
element_selection_state_to_be(element, is_selected):
检查一个元素的选中状态是否符合预期。
-
element_located_selection_state_to_be(locator, is_selected):
检查一个元素的选中状态是否可以符合预期。
-
alert_is_present():
检查是否有alert弹出。
2. ExpectedCondition类型是布尔的,成功的返回值就是true,其他类型的ExpectedCondition成功的返回值就是 not None;如果条件不成立,会在指定的超时时间内持续等待,直到超时后抛出TimeoutException异常。
3.示例
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
wait.until(EC.visibility_of(element))
wait.until(EC.element_to_be_clickable((by, value)))