1. 程式人生 > 其它 >web自動化學習06——元素等待

web自動化學習06——元素等待

在定位元素時,由於網路或其它的原因,定位的元素不能及時加載出來,此時需要等待一段時間後才能定位到指定元素,"等待一段時間"的方法有三種;

1)強制等待 time.sleep(等待時間),單位:s

2)隱式等待 :implicitly_wait(time),單位:s

3)顯示等待:WebDriverWait(驅動,timeout,poll_frequency=None,ignored_exceptions=None)

——driver:WebDriver 的驅動程式(Ie, Firefox, Chrome 或遠端)

——timeout:最長超時時間,預設以秒為單位

——poll_frequency:休眠時間的間隔(步長)時間,預設為 0.5 秒,每隔0.5s去定位一次元素

——ignored_exceptions:超時後的異常資訊,預設情況下拋 NoSuchElementException 異常

區別及優缺點:

1、強制等待(time.sleep()):在設定的時間範圍內,如設定5s,則在5s內不管元素是否定位到,都需要等待5s後再進行下一步。元素可能在第1s或第2s就定位到,但是需要等待5s,比較浪費時間。但是每次定位元素都需要在定位元素的程式碼前編寫顯示等待的程式碼。

2、隱式等待(implicitly()):在設定的時間範圍內,如設定5s,則在5s內定位的元素所在頁面全部載入完畢,則進行下一步。定位的元素可能在第1s或第2s就定位到,但此時頁面還未全部載入,需要繼續等待,存在一定時間的浪費;(只需要在程式碼最前方寫一次隱式等待的程式碼,後面定位的元素都會使用到)。

3、顯示等待(WebDriverWait()):在設定的時間範圍內,如設定5s,則在5s內定位到所需元素,則立即繼續下一步,無需等待頁面全部載入完成,不存在時間的浪費。但是每次定位元素都需要編寫顯示等待的程式碼。

from selenium import webdriver
from time import sleep
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
class elementLocator_waittime_style():

    
''' 元素等待方式: 1)強制等待:time.sleep(2) 2)顯示等待:WebdriverWait() 3)隱式等待:implicitly() ''' def __init__(self): #加啟動配置 option = webdriver.ChromeOptions() # 關閉“chrome正受到自動測試軟體的控制” option.add_experimental_option('useAutomationExtension',False) #不自動關閉瀏覽器 option.add_experimental_option('detach',True) self.driver = webdriver.Chrome(chrome_options=option) self.driver.get("http://www.baidu.com") self.driver.maximize_window() #強制等待 def elementLocator_waittime_sleep(self): #強制等待5s,等待頁面載入完成 sleep(5) #定位到搜尋輸入框 search_input = self.driver.find_element(By.ID,'kw') #輸入selenium等待時間 search_input.send_keys('selenium等待時間') #等待2s sleep(2) #定位到搜尋按鈕 search_button = self.driver.find_element(By.ID,'su') #點選搜尋按鈕 search_button.click() #等待3s關閉視窗 sleep(3) self.driver.close() #顯示等待 def elementLocator_waittime_webdriverwait(self): search_input = WebDriverWait(self.driver,30,poll_frequency=1,ignored_exceptions="未找到元素").until(lambda s:s.find_element(By.ID,'kw')) search_input.send_keys("顯性等待") #定位到搜尋按鈕 search_button = WebDriverWait(self.driver,30,poll_frequency=1,ignored_exceptions="未找到搜尋按鈕元素").until(lambda s:s.find_element(By.ID,'su')) #點選搜尋按鈕 search_button.click() #隱式等待 def elementLocator_waittime_implicitly_wait(self): ''' 30s內頁面載入完畢則進行下一步,否則一直等待30s :return: ''' self.driver.implicitly_wait(30) #定位百度搜索輸入框 search_input = self.driver.find_element(By.ID,'kw') #搜尋隱式等待 search_input.send_keys("隱式等待") #定位搜尋按鈕 search_button = self.driver.find_element(By.ID,'su') #點選搜尋按鈕 search_button.click() #等待3s關閉瀏覽 self.driver.quit() elementLocator_waittime_style().elementLocator_waittime_webdriverwait()