1.強制等待sleep()
使用方法:sleep(X),等待X秒后,進行下一步操作。
使用最簡單的一種辦法就是強制等待sleep(X),強制讓瀏覽器等待X秒,不管當前操作是否完成,是否可以進行下一步操作,都必須等X秒的時間。
缺點:不能准確把握需要等待的時間(有時操作還未完成,等待就結束了,導致報錯;有時操作已經完成了,但等待時間還沒有到,浪費時間)
優點:使用簡單,可以在調試時使用
2.隱式等待implicitly_wait()
使用方法:(WebDriver類下的)implicitly_wait(X),在X時間內,頁面加載完成,進行下一步操作
說明:首先Implicit Waits默認是等待時間是0,同時隱性等待是對driver起作用,所以只要設置一次即可,比強制等待更智能
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time
driver=webdriver.Firefox()
driver.get("https://www.baidu.com")
driver.implicitly_wait(5) #隱式等待時間設置5秒
#檢測搜索框是都存在
try:
print(time.ctime()) #打印當前時間,精確到秒
driver.find_element_by_id("kw").send_keys("python") #id 定位,最多等待5秒
driver.find_element_by_css_selector("#su").click() #最多等待5秒,隱式等待對這里的都起到作用,直接執行完
#如果出現了異常,則打印出來
except NoSuchElementException as mss:
print(mss)
finally:
print(time.ctime())
time.sleep(6)
driver.quit()
3.顯示等待 WebDriverWait()
需要先導入from selenium.webdriver.support.wait import WebDriverWait
WebDriverWait()會配合until()和until_not()方法一起使用
使用方法:
WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None).until(要執行的方法)
driver:瀏覽器實例
timeout:超時時間,默認已秒為單位
poll_frequency:檢測時間間隔,默認0.5秒
ignored_exceptions:報錯信息,默認拋出NoSuchElementException
WebDriverWait 類 :until() 和 until_not()
until():可以傳兩個參數,第一個參數是判斷條件,直到第一個參數返回True。第二個參數可以寫文字說明。直到條件成立返回為真,等待結束。如果超時,拋出TimeoutException,將message傳入異常
until_not():可以傳兩個參數,第一個參數是判斷條件,直到第二個參數返回 False。第二個參數可以寫文字說明。直到條件不成立返回為真,是當某元素消失或什么條件不成立則繼續執行,等待結束。如果超時,拋出TimeoutException,將message傳入異常
以下幾個條件驗證:
3.1驗證 title
title_is :驗證傳入的參數 title 是否等於 driver.title
title_contains :驗證傳入的參數 title 是否包含於 driver.title
3.2驗證元素是否出現,傳入的參數都是元組類型的 locator,如(By.ID,'kw')
presence_of_element_located :只要一個符合條件的元素加載出來就通過
presence_of_all_elements_located :必須所有符合條件的元素都加載出來才行
3.3驗證元素是否可見:
visibility_of_element_located :傳入的參數是元組類型的 locator
invisibility_of_element_located :傳入的參數是元組類型的 locator
visibility_of :傳入 WebElement,第一個和第三個是一樣的
3.4判斷某段文本是否出現在某元素中
text_to_be_present_in_element :判斷元素的 text
text_to_be_present_in_element_value :判斷元素的 value
3.5判斷 frame 是否可切入,可傳入 locator 元組或者直接傳入定位方式:id、name、index 或 WebElement
frame_to_be_available_and_switch_to_it
3.6判斷是否有 alert 出現
alert_is_present
3.7判斷元素是否可點擊,傳入 locator
element_to_be_clickable
3.8判斷元素是否被選中
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
3.9判斷一個元素是否仍在 DOM 中,傳入 WebElement 對象,可以判斷頁面是都刷新
staleness_of
3.10WebElement 自帶方法
is_displayed() :判斷元素是否展示出來
is_enabled() :判斷元素是否可操作
