from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC driver = webdriver.Firefox() driver.get("http://somedomain/url_that_delays_loading") try: element = WebDriverWait(driver, 10).until( //使用 WebDriverWait()来等待 最多等10秒来等待找到指定条件的元素, 超时未找到抛出TimeoutException EC.presence_of_element_located((By.ID, "myDynamicElement")) ) finally: driver.quit()
其他的EC方法 用于自动化浏览器
title_is title_contains presence_of_element_located visibility_of_element_located visibility_of presence_of_all_elements_located text_to_be_present_in_element text_to_be_present_in_element_value frame_to_be_available_and_switch_to_it invisibility_of_element_located element_to_be_clickable staleness_of element_to_be_selected element_located_to_be_selected element_selection_state_to_be element_located_selection_state_to_be alert_is_present
例如:
from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10) element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))
也可创建自定义等待条件。可以使用带有__call__方法的类创建自定义等待条件,当条件不匹配时,该方法将返回False。
1 class element_has_css_class(object): //自定义的方法 2 """An expectation for checking that an element has a particular css class. 3 4 locator - used to find the element 5 returns the WebElement once it has the particular css class 6 """ 7 def __init__(self, locator, css_class): 8 self.locator = locator 9 self.css_class = css_class 10 11 def __call__(self, driver): 12 element = driver.find_element(*self.locator) # Finding the referenced element 13 if self.css_class in element.get_attribute("class"): 14 return element 15 else: 16 return False 17 18 # Wait until an element with id='myNewInput' has class 'myCSSClass' 19 wait = WebDriverWait(driver, 10) 20 element = wait.until(element_has_css_class((By.ID, 'myNewInput'), "myCSSClass")) // 先通过 init方法 call 方法
3.默认等待
1 from selenium import webdriver 2 3 driver = webdriver.Firefox() 4 driver.implicitly_wait(10) # seconds 5 driver.get("http://somedomain/url_that_delays_loading") 6 myDynamicElement = driver.find_element_by_id("myDynamicElement")
标签:webdriver,selenium,driver,page,objects,element,class,css From: https://www.cnblogs.com/shaitaiyang/p/16778301.html