為了保證腳本的穩定性,有時候需要引入等待時間,等待頁面加載元素后再進行操作,selenium提供三種等待時間設置方式。
1、sleep():固定休眠時間設置
import time time.sleep(1)
2、implicitlyWait() :隱式等待、全局等待
機制:每隔500毫秒在界面進行一次檢查 檢查到了就不等待了 在規定的時間內檢查不到就會報錯
driver.implicitly_wait(4)
3、WebDriverWait():顯示等待
語法格式如下:
WebDriverWait(driver,timeout,poll_frequency=0.5,ignore_exceptions=None)
driver:WebDriver的驅動程序(IE,火狐,谷歌或遠程)
timeout:最長超時時間,默認以秒為單位
poll_frequency:休眠時間的間隔(步長)時間,默認為0.5秒(即每500毫秒掃描一次頁面)
ignore_exceptions:超時后的的異常信息,默認情況下拋NoSuchElementException異常
#顯示等待 比較難寫 # poll_frequency 間隔檢查時間 根據設置的時間 檢查一次 默認是500毫秒檢查一次
from selenium.webdriver.support.wait import WebDriverWait driver_wait=WebDriverWait(driver,20,poll_frequency=1) element=driver_wait.until(lambda x:x.find_element(By.XPATH,'//div')) print(element.get_attribute('class'))