Selenium-Webdriver API命令和操作-Get & Wait


抓取頁面

WebDriver可能要做的第一件事就是導航到一個頁面。正常的做法是調用“get”:

drviver.get("http://www.google.com")

取決於幾個因素,包括操作系統/瀏覽器組合,WebDriver可能會或可能不會等待頁面加載。在某些情況下,WebDriver可能會在頁面完成之前或者甚至開始加載之前返回控件。為確保健壯性,需要使用顯式和隱式等待來等待頁面中存在的元素 

顯式等待

明確的等待是定義的代碼,等待一定的條件發生,然后繼續進行代碼。最糟糕的情況是Thread.sleep(),它將條件設置為等待的確切時間段。有一些方便的方法可以編寫只需要等待的代碼。WebDriverWait與ExpectedCondition結合是可以完成的一種方法。

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 

ff = webdriver.Firefox()
ff.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(ff, 10).until(EC.presence_of_element_located((By.ID, "myDynamicElement")))
finally:
    ff.quit()

在等待10秒之前拋出一個TimeoutException,或者如果它發現元素將在0-10秒內返回。WebDriverWait默認每500毫秒調用ExpectedCondition,直到成功返回。ExpectedCondition函數類型的成功返回值是布爾值true或非空對象。這個例子在功能上也等同於下一個Implicit Waits例子:

from selenium import webdriver

ff = webdriver.Firefox()
ff.implicitly_wait(10) # seconds
ff.get("http://somedomain/url_that_delays_loading")
myDynamicElement = ff.find_element_by_id("myDynamicElement")

自動化瀏覽器時,經常遇到一些常見的情況。下面列出的是使用這些條件的幾個例子。Python綁定包括convenience方法,因此不必親自編寫ExpectedCondition類或為其創建自己的實用程序包。

from selenium.webdriver.support import expected_conditions as EC
wait = WebDriverWait(driver, 10)
element = wait.until(EC.element_to_be_clickable((By.ID,'someid')))

ExpectedConditions包包含一組與WebDriverWait一起使用的預定義條件。

隱等待

一個隱含的等待就是告訴WebDriver在查找一個或多個元素(如果不是立即可用的)時輪詢DOM一段時間。默認設置為0.一旦設置,隱式等待就設置為WebDriver對象實例的生命周期。

from selenium import webdriver

ff = webdriver.Firefox()
ff.implicitly_wait(10) # seconds
ff.get("http://somedomain/url_that_delays_loading")
myDynamicElement = ff.find_element_by_id("myDynamicElement")

 


免責聲明!

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



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