Python3關於selenium的強制等待、隱式等待和顯式等待(附上EC的主要方法)

強制等待

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
print(driver.current_url)
time.sleep(3)
driver.quit()
  • 分析:強制等待,死板且不靈活,若等待時間過長則嚴重影響程序執行速度

隱式等待

from selenium import webdriver
import time
driver = webdriver.Chrome()
driver.get('https://www.baidu.com')
print(driver.current_url)
driver.implicitly_wait(30)
driver.quit()
  • 分析:隱形等待是設置了一個最長等待時間,如果在規定時間內網頁加載完成,則執行下一步,否則一直等到時間截止,然後執行下一步。注意這裏有一個弊端,那就是程序會一直等待整個頁面加載完成,也就是一般情況下你看到瀏覽器標籤欄那個小圈不再轉,纔會執行下一步,但有時候頁面想要的元素早就在加載完成了,但是因爲個別js之類的東西特別慢,我仍得等到頁面全部完成才能執行下一步,我想等我要的元素出來之後就下一步怎麼辦?有辦法,這就要看selenium提供的另一種等待方式——顯性等待wait了。

需要特別說明的是:隱性等待對整個driver的週期都起作用,所以只要設置一次即可,我曾看到有人把隱性等待當成了sleep在用,走哪兒都來一下

顯性等待

WebDriverWait爲顯型等待,配合until()和until_not()方法,就能夠根據EC而進行靈活地等待了。它主要的意思就是:程序每隔xx秒看一眼,如果條件成立了,則執行下一步,否則繼續等待,直到超過設置的最長時間,然後拋出TimeoutException。

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait

driver = webdriver.Chrome()
# 第二個參數30,表示等待的最長時間,超過30秒則拋出TimeoutException
# 第三個參數0.2,表示0.2秒去檢查一次
wait = WebDriverWait(driver, 30, 0.2)
driver.get('https://www.baidu.com')
wait.until(EC.presence_of_element_located((By.ID, "lg")))
print(driver.current_url)
driver.quit()
until

method: 在等待期間,每隔一段時間(__init__中的poll_frequency)調用這個傳入的方法,直到返回值不是False
message: 如果超時,拋出TimeoutException,將message傳入異常

until_not

與until相反,until是當某元素出現或什麼條件成立則繼續執行, until_not是當某元素消失或什麼條件不成立則繼續執行,參數也相同,不再贅述。

expected_conditions

expected_conditions是selenium的一個模塊,其中包含一系列可用於判斷的條件:

selenium.webdriver.support.expected_conditions(模塊)

以下兩個條件類驗證title,驗證傳入的參數title是否等於或包含於driver.title
title_is
title_contains

以下兩個條件驗證元素是否出現,傳入的參數都是元組類型的locator,如(By.ID, ‘kw’)
顧名思義,一個只要一個符合條件的元素加載出來就通過;另一個必須所有符合條件的元素都加載出來纔行
presence_of_element_located
presence_of_all_elements_located

以下三個條件驗證元素是否可見,前兩個傳入參數是元組類型的locator,第三個傳入WebElement
第一個和第三個其實質是一樣的
visibility_of_element_located
invisibility_of_element_located
visibility_of

以下兩個條件判斷某段文本是否出現在某元素中,一個判斷元素的text,一個判斷元素的value
text_to_be_present_in_element
text_to_be_present_in_element_value

以下條件判斷frame是否可切入,可傳入locator元組或者直接傳入定位方式:id、name、index或WebElement
frame_to_be_available_and_switch_to_it

以下條件判斷是否有alert出現
alert_is_present

以下條件判斷元素是否可點擊,傳入locator
element_to_be_clickable

以下四個條件判斷元素是否被選中,第一個條件傳入WebElement對象,第二個傳入locator元組
第三個傳入WebElement對象以及狀態,相等返回True,否則返回False
第四個傳入locator以及狀態,相等返回True,否則返回False
element_to_be_selected
element_located_to_be_selected
element_selection_state_to_be
element_located_selection_state_to_be

最後一個條件判斷一個元素是否仍在DOM中,傳入WebElement對象,可以判斷頁面是否刷新了
staleness_of

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章