標籤:設定 send 直接 強制 exp dom baidu contains 判斷
如果遇到使用ajax載入的網頁,頁面元素可能不是同時載入出來的,這個時候,就需要我們通過設定一個等待條件,等待頁面元素載入完成,避免出現因為元素未載入導致的錯誤的出現。
WebDriver提供了兩種等待類型:顯示等待、隱式等待。
1.顯示等待:WebDriverWait()類
- 顯示等待:設定一個等待時間和一個條件,在規定時間內,每隔一段時間查看下條件是否成立,如果成立那麼程式就繼續執行,否則就提示一個逾時異常(TimeoutException)。
- 通常情況下WebDriverWait類會結合ExpectedCondition類一起使用。
執行個體:
from selenium import webdriverfrom selenium.webdriver.support.wait import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as ECfrom selenium.webdriver.common.by import Bydriver = webdriver.Chrome()driver.get(‘https://www.baidu.com‘)# 設定瀏覽器:driver 等待時間:20swait = WebDriverWait(driver, 20)# 設定判斷條件:等待id=‘kw‘的元素載入完成input_box = wait.until(EC.presence_of_element_located((By.ID, ‘kw‘)))# 在關鍵詞輸入:關鍵詞input_box.send_keys(‘關鍵詞‘)
WebDriverWait的具體參數和方法:
WebDriverWait(driver,timeout,poll_frequency=0.5,ignored_exceptions=None) driver: 瀏覽器驅動 timeout: 逾時時間,等待的最長時間(同時要考慮隱性等待時間) poll_frequency: 每次檢測的間隔時間,預設是0.5秒 ignored_exceptions:逾時後的異常資訊,預設情況下拋出NoSuchElementException異常until(method,message=‘‘) method: 在等待期間,每隔一段時間調用這個傳入的方法,直到傳回值不是False message: 如果逾時,拋出TimeoutException,將message傳入異常until_not(method,message=‘‘) until_not 與until相反,until是當某元素出現或什麼條件成立則繼續執行, until_not是當某元素消失或什麼條件不成立則繼續執行,參數也相同。 method message
ExpectedCondition
- ExpectedCondition中可使用的判斷條件:
from selenium.webdriver.support import expected_conditions as EC# 判斷標題是否和預期的一致title_is# 判斷標題中是否包含預期的字串title_contains# 判斷指定元素是否載入出來presence_of_element_located# 判斷所有元素是否載入完成presence_of_all_elements_located# 判斷某個元素是否可見. 可見代表元素非隱藏,並且元素的寬和高都不等於0,傳入參數是元群組類型的locatorvisibility_of_element_located# 判斷元素是否可見,傳入參數是定位後的元素WebElementvisibility_of# 判斷某個元素是否不可見,或是否不存在於DOM樹invisibility_of_element_located# 判斷元素的 text 是否包含預期字串text_to_be_present_in_element# 判斷元素的 value 是否包含預期字串text_to_be_present_in_element_value#判斷frame是否可切入,可傳入locator元組或者直接傳入定位方式:id、name、index或WebElementframe_to_be_available_and_switch_to_it#判斷是否有alert出現alert_is_present#判斷元素是否可點擊element_to_be_clickable# 判斷元素是否被選中,一般用在下拉式清單,傳入WebElement對象element_to_be_selected# 判斷元素是否被選中element_located_to_be_selected# 判斷元素的選中狀態是否和預期一致,傳入參數:定位後的元素,相等返回True,否則返回Falseelement_selection_state_to_be# 判斷元素的選中狀態是否和預期一致,傳入參數:元素的定位,相等返回True,否則返回Falseelement_located_selection_state_to_be#判斷一個元素是否仍在DOM中,傳入WebElement對象,可以判斷頁面是否重新整理了staleness_of
調用方法如下:
WebDriverWait(driver, 逾時時間長度, 調用頻率, 忽略異常).until(可執行方法, 逾時時返回的資訊)
2.隱式等待
- implicitly_wait(xx):設定等待時間為xx秒,等待元素載入完成,如果到了時間元素沒有載入出,就拋出一個NoSuchElementException的錯誤。
- 注意:隱性等待對整個driver的周期都起作用,所以只要設定一次即可。
from selenium import webdriverdriver = webdriver.Chrome()driver.implicitly_wait(30) # 隱性等待,最長等30秒driver.get(‘https://www.baidu.com‘)print(driver.current_url)print(driver.title)
3.強制等待:sleep()
- 強制等待:不管瀏覽器元素是否載入完成,程式都得等待3秒,3秒一到,繼續執行下面的代碼。
from selenium import webdriverfrom time import sleepdriver = webdriver.Chrome()driver.get(‘https://www.baidu.com‘)sleep(3) # 強制等待3秒再執行下一步print(driver.title)
Python+Selenium自動化篇-8-設定等待三種等待方法