Python 中 Selenium 的隱式等待是什麼?
在使用 Selenium 時,可能會遇到這種情況:瀏覽器載入頁面後,網頁元素會在不同的時間間隔內載入。
這種型別的狀況會導致 Selenium 和頁面上的網頁元素之間出現同步問題。由於 DOM 中不存在該元素,因此無法識別元素。由於此原因,會丟擲 ElementNotVisibleException 等異常。
Selenium 中的等待概念克服了這個問題,並在元素識別和對其執行操作之間設定了延遲。隱式等待可以被認為是測試用例中測試步驟的預設等待時間。
隱式等待是應用於頁面上所有元素的全域性等待。等待時間作為引數提供給方法。例如,如果等待時間為 5 秒,則它將在丟擲超時異常之前等待此時間段。
隱式等待是動態等待,這意味著如果元素在第三秒可用,那麼我們將繼續執行測試用例的下一步,而不是等待全部五秒。
隱式等待指示 Web 驅動程式輪詢特定時間段。確定此時間後,它將保留整個驅動程式會話。隱式等待的預設時間為 0。
語法
driver.implicitly_wait(2)
下面列出了隱式等待的一些缺點:
- 測試執行時間增加。
- 無法捕獲應用程式中與效能相關的問題。
示例
使用隱式等待的程式碼實現。
from selenium import webdriver #browser exposes an executable file #Through Selenium test we will invoke the executable file which will then #invoke actual browser driver = webdriver.Chrome(executable_path="C:\chromedriver.exe") #setting implicit wait 5 seconds driver.implicitly_wait(5) # to maximize the browser window driver.maximize_window() #get method to launch the URL driver.get("https://tutorialspoint.tw/about/about_careers.htm") #to refresh the browser driver.refresh() # identifying the link with link_text locator driver.find_element_by_link_text("Company").click() #to close the browser driver.quit()
廣告