selenium---常用元素等待的三種方法


  在寫appium的時候介紹了等待時間,其實selenium這里也是一樣的,分別是強制等待,隱式等待,顯示等待。詳情見:appium---等待時間

強制等待

看到名稱就應該知道,強制等待,就是設置多少秒,就必須等待多少秒,才能繼續往下面操作

time.sleep()

def sleep(seconds): # real signature unknown; restored from __doc__
    """
    sleep(seconds)
    
   延遲指定的秒數
    """
    pass

使用方法

# 直接在需要等待的地方添加
import time
time.sleep(10)

隱式等待

隱式等待:  implicitly_wait?()  默認參數的單位為妙,設置一個等待時間,它並不影響腳本的執行速度。當腳本執行到某個元素定位是,如果元素可以定位,則繼續執行,如果元素定位不到,則它將以輪詢的方式不斷地判斷元素是否被定位到。假設在第六秒定位到了元素則繼續執行,若直到超出設置的時長10秒還沒有定位到元素,則拋出異常。

源碼:

def implicitly_wait(self, time_to_wait):
        """
        Sets a sticky timeout to implicitly wait for an element to be found,
           or a command to complete. This method only needs to be called one
           time per session. To set the timeout for calls to
           execute_async_script, see set_script_timeout.

        :Args:
         - time_to_wait: Amount of time to wait (in seconds)

        :Usage:
            driver.implicitly_wait(30)
        """
        if self.w3c:
            self.execute(Command.SET_TIMEOUTS, {
                'implicit': int(float(time_to_wait) * 1000)})
        else:
            self.execute(Command.IMPLICIT_WAIT, {
                'ms': float(time_to_wait) * 1000})

使用方法:

# 在需要等待的地方直接添加
driver.implicitly_wait(10)

顯示等待

顯式等待是WebDriver等待某個條件成立則繼續執行,在等待的時間內,可以多少秒進行查看,看等待條件是否出現。否則在達到最大時長時拋出超時異常(TimeoutException)

源碼:

 

def __init__(self, driver, timeout, poll_frequency=POLL_FREQUENCY, ignored_exceptions=None):
        """
    driver: 返回一個webdriver實例化
    timeout:設置一個超時時長(S)
    poll_frequency:循環讀取元素的時間,默認是0.5(s)
  
            使用方法 :
            from selenium.webdriver.support.ui import WebDriverWait \n
            element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId")) \n
            is_disappeared = WebDriverWait(driver, 30, 1, (ElementNotVisibleException)).\ \n
                        until_not(lambda x: x.find_element_by_id("someId").is_displayed())
        """
        self._driver = driver
        self._timeout = timeout
        self._poll = poll_frequency
        # avoid the divide by zero
        if self._poll == 0:
            self._poll = POLL_FREQUENCY
        exceptions = list(IGNORED_EXCEPTIONS)
        if ignored_exceptions is not None:
            try:
                exceptions.extend(iter(ignored_exceptions))
            except TypeError:  # ignored_exceptions is not iterable
                exceptions.append(ignored_exceptions)
        self._ignored_exceptions = tuple(exceptions)

從源碼中分許出來三個參數的作用

driver:返回一個webdriver實例化

timeout:設置一個超時時長

poll_frequentcy:循環讀取元素時間

ignored_exceptions:報錯信息

WebDriverWait一般與until()或until_not()方法配合使用。

until表示:提供一個參數,返回值為True

until_not表示:提供一個參數,返回值為Flase

使用方法:

from selenium.webdriver.support.ui import WebDriverWait

element = WebDriverWait(driver, 10).until(lambda x: x.find_element_by_id("someId"))

一般顯示等待可以和EC(expected_conditions)元素等待進行一起使用。

from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.implicitly_wait(10) # 隱性等待和顯性等待可以同時用,但要注意:等待的最長時間取兩者之中的大者
driver.get('https://www.baidu.com')
locator = (By.ID, 'kw')
# 判斷元素是否出現 WebDriverWait(driver,
20,0.5).until(EC.presence_of_element_located(locator))

 

如果安靜寫的有不懂的或者寫錯的地方,都可以下方留言,安靜看到后第一時間進行回復,持續更新~~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM