1. expected_conditions 模块
我们看一下 expected_conditions 提供的条件有哪些:
from selenium.webdriver.support import expected_conditions
---------------------------------------------------------
# 以下两个条件类验证title,验证传入的参数title是否等于或包含于driver.title
title_is
title_contains
# 以下四个条件类验证url,验证driver.current_url
url_contains # 传入url,包含时返回true
url_matches # 传入正则表达式
url_to_be # 传url,完全匹配时返回true
url_changes # 传url,不匹配时返回true
# 以下两个条件验证元素是否出现,传入的参数都是元组类型的locator
presence_of_element_located
presence_of_all_elements_located
# 以下三个条件验证元素是否可见,前两个传入参数是元组类型的locator,第三个传入WebElement
visibility_of # 传入WebElement
visibility_of_element_located # 传入元组类型的locator
visibility_of_any_elements_located # 传入元组类型的locator
visibility_of_all_elements_located # 传入元组类型的locator
invisibility_of_element # 传入WebElement 或 locator
invisibility_of_element_located # 传入元组类型的locator
# 以下两个条件判断某段文本是否出现在某元素中,一个判断元素的text,一个判断元素的value
text_to_be_present_in_element
text_to_be_present_in_element_value
# 以下条件判断frame是否可切入,可切入则切入指定frame
frame_to_be_available_and_switch_to_it
# 以下条件判断元素是可见的并且可被点击
element_to_be_clickable
# 以下条件等某个结点从DOM树中移除,如果该元素仍然存在则返回false,否则返回true,常用于判断页面是否已刷新
staleness_of
# 以下四个条件判断元素是否被选中
element_to_be_selected # 传入WebElement对象
element_located_to_be_selected # 传入元组类型的locator
element_selection_state_to_be # 传入WebElement对象以及状态,相等返回True,否则返回False
element_located_selection_state_to_be # 传入locator以及状态,相等返回True,否则返回False
# 以下条件判断窗口数量,传入期望窗口数
number_of_windows_to_be
# 以下条件判断是否打开一个新窗口,并且窗口句柄数量会增加
new_window_is_opened
# 以下条件判断是否有alert出现
alert_is_present
2. 使用场景
expected_conditions 模块最常见的就是与 WebDriverWait 配合使用,如:
import time
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.Chrome()
driver.maximize_window()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com/")
locator = ("id", "kw")
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located(locator))
element.send_keys("hwijew")
time.sleep(2)
driver.quit()
WebDriverWait 详情请看 Selenium系列教程 - WebDriverWait 详解以及自定义判断条件