webdriver三種等待方法
1.使用WebDriverWait
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
element = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")))
finally:
driver.quit()
presence_of_element_located可以替換為
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 - it is Displayed and Enabled.
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
By.ID中的ID可替換為'CLASS_NAME', 'CSS_SELECTOR', 'ID', 'LINK_TEXT', 'NAME', 'PARTIAL_LINK_TEXT', 'TAG_NAME', 'XPATH'
2、隱式等待,相當(dāng)于設(shè)置全局的等待,在定位元素時(shí),對(duì)所有元素設(shè)置超時(shí)時(shí)間。
隱式等待使得WebDriver在查找一個(gè)Element或者Element數(shù)組時(shí),每隔一段特定的時(shí)間會(huì)輪詢一次DOM,如果Element或數(shù)組沒有馬上被發(fā)現(xiàn)的話。
默認(rèn)設(shè)置是0。
一旦設(shè)置,這個(gè)隱式等待會(huì)在WebDriver對(duì)象實(shí)例的整個(gè)生命周期起作用。
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(10) # seconds
driver.get(http://www.xxx.com)
myDynamicElement = driver.find_element_by_id("ElementID")
3、強(qiáng)制等待
import time
time.sleep(10)