selenium 的等待方式,常見有下列3種,使用上各有優缺點。這篇文章的重點在「顯性等待」,使用 WebDriverWait 配合until()和until_not()方法。
强制等待
-- coding: utf-8 --
from selenium import webdriver
from time import sleep
driver = webdriver.Firefox()
driver.get('https://your.url')
sleep(3) # 强制等待3秒再执行下一步
print driver.current_url
driver.quit()
隱性等待
隱形等待是設置了一個最長等待時間,如果在規定時間內網頁加載完成,則執行下一步,否則一直等到時間截止,然後執行下一步。注意這裡有一個弊端,那就是程序會一直等待整個頁面加載完成。
-- coding: utf-8 --
from selenium import webdriver
driver = webdriver.Firefox()
driver.implicitly_wait(30) # 隐性等待,最长等30秒
driver.get('https://your.url')
print driver.current_url
driver.quit()
顯性等待
詳細介紹:
https://selenium-python-zh.readthedocs.io/en/latest/waits.html
或:
https://selenium-python.readthedocs.io/waits.html
WebDriverWait,配合until()和until_not()方法,就能夠根據判斷條件而進行靈活地等待了。它主要的意思就是:如果條件成立了,則執行下一步,否則繼續等待,直到超過設置的最長時間,然後拋出TimeoutException。
-- coding: utf-8 --
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Firefox()
driver.implicitly_wait(10)
# 隐性等待和显性等待可以同时用,但要注意:等待的最长时间取两者之中的大者
driver.get('https://your.url')
locator = (By.LINK_TEXT, 'CSDN')
try:
WebDriverWait(driver, 20, 0.5).until(EC.presence_of_element_located(locator))
print driver.find_element_by_link_text('CSDN').get_attribute('href')
finally:
driver.close()
範例2:
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( EC.presence_of_element_located((By.ID, "myDynamicElement")) ) finally:
driver.quit()
範例3:
from selenium.webdriver.support import expected_conditions as EC wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID, 'someid')))
Expected Conditions
There are some common conditions that are frequently of use when automating web browsers. Listed below are the names of each. Selenium Python binding provides some convenience methods so you don’t have to code an expected_condition class yourself or create your own utility package for them.
- 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