Python爬蟲 - Selenium(13)設置元素等待

WebDriver提供了兩種類型的等待:顯式等待和隱式等待。顯式等待是給每一個條件都單獨設置等待時間,而隱式等待是設置一個統一的等待時間。個人比較推薦隱式等待,至於原因,大家看過就知道了。

一、顯式等待

WebDriverWait類是由WebDirver 提供的等待方法。在設置時間內,默認每隔一段時間檢測一次當前頁面元素是否存在,如果超過設置時間檢測不到則拋出異常(TimeoutException)

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
import time

driver = webdriver.Chrome()
driver.get('https://www.baidu.com/')

element = WebDriverWait(driver, 5, 0.5).until(
                      EC.presence_of_element_located((By.ID, "kw"))
                      )
element.send_keys('selenium')
time.sleep(5)

driver.quit()

語法:

WebDriverWait(driver, timeout, poll_frequency=0.5, ignored_exceptions=None).until(method, message=‘’)

參數說明如下:

  • driver:瀏覽器驅動
  • timeout:最長超時時間,默認以秒爲單位
  • poll_frequency:檢測的間隔時間,默認爲0.5s
  • ignored_exceptions:超時後的異常信息,默認情況下拋NoSuchElementException異常
  • until(method, message=‘’):調用該方法提供的驅動程序作爲一個參數,直到返回值爲True
  • until_not(method, message=‘’):調用該方法提供的驅動程序作爲一個參數,直到返回值爲False
  • presence_of_element_located():判斷元素是否存在。

二、隱式等待

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time

driver = webdriver.Chrome()

# 設置隱式等待爲5秒
driver.implicitly_wait(5)
driver.get("http://www.baidu.com")

try:
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    driver.find_element_by_id("123456").send_keys('selenium') #不存在的id,看輸出報錯和時間
    # driver.find_element_by_id("kw").send_keys('selenium') # 存在的id
except NoSuchElementException as e:
    print(e)
finally:
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    driver.quit()

implicitly_wait() 默認0,參數的單位爲秒,上邊設置的等待時間爲5秒,這個時間不像time.sleep(5)那樣直接睡5秒;當執行流程到某個元素定位時,如果元素可以定位,則繼續執行;如果元素定位不到,則它將以循環的方式不斷地判斷元素是否被定位到。比如說在1秒的時候定位到了,那麼直接向下運行如果超出設置時長,則拋出異常。

Selenium文集傳送門:

標題 簡介
Python爬蟲 - Selenium(1)安裝和簡單使用 詳細介紹Selenium的依賴環境在Windows和Centos7上的安裝及簡單使用
Python爬蟲 - Selenium(2)元素定位和WebDriver常用方法 詳細介紹定位元素的8種方式並配合點擊和輸入、提交、獲取斷言信息等方法的使用
Python爬蟲 - Selenium(3)控制瀏覽器的常用方法 詳細介紹自定義瀏覽器窗口大小或全屏、控制瀏覽器後退、前進、刷新瀏覽器等方法的使用
Python爬蟲 - Selenium(4)配置啓動項參數 詳細介紹Selenium啓動項參數的配置,其中包括無界面模式、瀏覽器窗口大小設置、瀏覽器User-Agent (請求頭)等等
Python爬蟲 - Selenium(5)鼠標事件 詳細介紹鼠標右擊、雙擊、拖動、鼠標懸停等方法的使用
Python爬蟲 - Selenium(6)鍵盤事件 詳細介紹鍵盤的操作,幾乎包含所有常用按鍵以及組合鍵
Python爬蟲 - Selenium(7)多窗口切換 詳細介紹Selenium是如何實現在不同的窗口之間自由切換
Python爬蟲 - Selenium(8)frame/iframe表單嵌套頁面 詳細介紹如何從當前定位的主體切換爲frame/iframe表單的內嵌頁面中
Python爬蟲 - Selenium(9)警告框(彈窗)處理 詳細介紹如何定位並處理多類警告彈窗
Python爬蟲 - Selenium(10)下拉框處理 詳細介紹如何靈活的定位並處理下拉框
Python爬蟲 - Selenium(11)文件上傳 詳細介紹如何優雅的通過send_keys()指定文件進行上傳
Python爬蟲 - Selenium(12)獲取登錄Cookies,並添加Cookies自動登錄 詳細介紹如何獲取Cookies和使用Cookies進行自動登錄
Python爬蟲 - Selenium(13)設置元素等待 詳細介紹如何優雅的設置元素等待時間,防止程序運行過快而導致元素定位失敗
Python爬蟲 - Selenium(14)窗口截圖 詳細介紹如何使用窗口截圖
Python爬蟲 - Selenium(15)關閉瀏覽器 詳細介紹兩種關閉窗口的區別

歡迎留言吐槽

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