您現在的位置是:首頁 > 單機遊戲首頁單機遊戲

在 Python 中使用 Selenium 等待頁面載入「教程」

簡介最常見的 EC 包括:Alert_is_presentElement_to_be_clickableElement_to_be_selectedFrame_to_be_available_and_switch_to_itNew_window

怎麼連線專用網路

每日分享最新,最流行的軟體開發知識與最新行業趨勢,希望大家能夠一鍵三連,多多支援,跪求關注,點贊,留言。

深入瞭解此 Python Selenium 等待教程,並找到使用 Selenium 等待頁面載入及其在 Python 中實現的需要的答案。

自動化與 DOM 中的 WebElement 互動的主要要求之一是它應該是可見且難以處理的。像我一樣,您也會遇到 Selenium Python 指令碼丟擲 ElementNotVisibleException 的幾種情況。

測試自動化指令碼中的失敗可歸因於網頁上存在動態 WebElement。被測 WebElement 可能尚未載入到網頁上,並且您的測試正嘗試在該 WebElement 上執行某些活動。眾所周知,使用 AJAX 進行動態內容載入被廣泛用於不同的 Web 產品(或網站)。使用 Selenium 測試自動化與動態 WebElement 互動時,建議新增 Selenium 以等待頁面載入,以便該元素可用於執行測試。

在 Python 中使用 Selenium 等待頁面載入「教程」

Python 中的 Selenium 等待為在 DOM 中載入 WebElement 提供了額外的時間。在本文中,我們深入探討了Selenium WebDriver中不同型別的等待以及 Selenium在 Python 中等待頁面載入的用法。

為什麼使用 Selenium 等待頁面載入?

要回答這個問題,必須瞭解動態頁面載入的“位置”和“原因”。下面提到的一些情況您可能已經知道,或者您可能已經遇到過。

1.上傳檔案

我相信您可能已經在某些線上平臺上上傳了一些檔案、影象或影片。您可能已經注意到,一旦您選擇了檔案,上傳該檔案需要一些時間。同理,當您嘗試使用 Selenium 測試自動化指令碼上傳檔案時,您需要在 Python 中實現 Selenium Wait 才能實現檔案的成功上傳。成功地。如果您不使用 Selenium 並在上傳後等待頁面載入,您可能會看到一些錯誤。

2. 延遲確認訊息

Gmail 等應用程式允許使用者實時互動和工作。即使您可以透過電子郵件傳送用例與應用程式互動,您也不會立即得到交付確認。確認取決於許多因素,例如網路可用性、附件大小等。

QA 工程師在計劃和執行可用性和使用者驗收測試時需要考慮這些條件。對於 Python,您必須實現 Selenium 等待頁面載入,以確保使用 DOM 中的必要 WebElement 執行測試。

3.頁面元素的條件載入

某些網站的某些元件或元素在初始階段隱藏或不可見。只有在滿足某些預設條件後才能與它們互動。例如——在電影票務網站上,預訂座位的按鈕只有在預設時間後才可用。這是頁面元件條件載入的經典案例。要在測試自動化指令碼中處理此類場景,您必須實現 Selenium 以等待頁面載入。

Selenium 正在等待確保頁面載入適用於其他場景,例如跳過 YouTube 上的廣告、延遲載入、延遲載入網頁中的影象等等。

該認證面向希望在使用 Python 進行 Selenium 自動化測試方面開發高階實踐專業知識並將其職業生涯提升到新水平的專業人士。

不同型別的 Python Selenium 等待

Selenium WebDriver 提供了一個“等待”包來處理在與目標 WebElement 互動之前需要等待的情況。您還可以利用 Python 的“睡眠”功能等待指定的時間間隔;但是,不推薦這種方法!

有三種不同的方法可以在 Python 中實現 Selenium Wait 以載入頁面:

顯式等待

隱式等待

流利的等待

Selenium Python 中的顯式等待

引入顯式等待以暫時凍結 Selenium 測試自動化指令碼的執行。它利用了 Selenium WebDriver 的等待包中提供的功能。程式暫停執行一段指定的時間或直到滿足某個預期條件。

可以使用 Selenium python 繫結的 WebDriverWait 類來實現顯式等待。讓我們看一下 WebDriverWait 類。

class selenium。webdriver。support。wait。WebDriverWait(driver, timeout, poll_frequency=0。5, ignored_exceptions=None)

如您所見,它接受兩個強制引數:驅動程式和超時;和兩個可選引數:poll_frequency 和ignore_exceptions

Driver

— 這是您用於執行應用程式測試的 WebDriver 例項。示例——Chrome、Remote、Firefox 等,

Timeout

— 它指的是等待失敗並引發異常之前的秒數。

Poll_frequency

— 輪詢頻率(可選引數)是 WebDriverWait 呼叫以再次檢查條件之前的等待/睡眠時間間隔。預設情況下,在 Selenium 中為 500 毫秒。您可以根據需要修改該值。如果您將 poll_frequency 傳遞為“0”,WebDriverWait __init__ 建構函式會將其設定回 0。5,這是兩個回撥之間的預設等待時間。

Ignored_exceptions

— WebDriverWait __init__ 建構函式的實現方式預設忽略 NoSuchElementException。如果您的 Selenium 測試自動化指令碼要求您忽略更多異常,則將異常列表傳遞給 ignored_exceptions 屬性。WebDriverWait 建構函式透過迭代您傳遞的列表來擴充套件其要忽略的異常列表。

除了 __init__ 之外,WebDriverWait 類還包含 __repr__ 物件函式,該函式在物件上呼叫 repr() 函式時以字串格式返回物件表示。簡而言之,WebDriverWait 類的其他函式使用 repr() 函式來記錄有關呼叫它的物件的有用資訊。

WebDriverWait 類中用於引入條件的兩個重要函式是until 和until_not。

until(self, method, message=‘’):這接受一個方法作為引數和一個可選訊息。until 在固定的時間跨度(即 poll_frequency [500ms 預設值])之後重複呼叫此方法。只有當返回值不為“False”時,指定方法的呼叫才會停止,即,直到該方法返回 Success。

until_not(self, method, message=‘’): until_not 很像直到。唯一的區別是 until_not 以固定的時間間隔 [poll_frequency] 重複呼叫該方法,如果它的計算結果為 True。通常,當您想等到元素消失時使用它。

WebDriverWait 引發 TimeoutException 如果該方法不返回真直到直到或假為 until_not。

例子:

WebDriverWait(driver, 10)。until(EC。presence_of_element_located((By。ID, “waitCreate”)))

Selenium 中的預期條件是 Selenium 的 WebDriverWait 類中使用頻率很高的便利類。最常見的 EC 包括:

Alert_is_present

Element_to_be_clickable

Element_to_be_selected

Frame_to_be_available_and_switch_to_it

New_window_is_opened

Number_of_windows_to_be

Presence_of_element_located

Text_to_be_present_in_element

Title_contains

Title_is

Url_changes

Url_contains

Url_matches

觀看此影片以瞭解 Selenium 中的等待以及如何使用不同的方法處理它們,例如硬編碼暫停以及將顯式等待與不同的設計模式相結合。

Selenium Python 中的隱式等待

隱式等待是使用

implicitly_wait(time_to_wait)

函式實現的。這會為每個會話設定一個粘性超時(即等待執行命令或在會話中查詢元素的時間)。Selenium 中的隱式等待和顯式等待之間存在很大差異。

在這裡,WebDriver 在丟擲異常之前輪詢 DOM 以在指定的持續時間內找到 WebElement。預設 time_to_wait 引數值設定為“0”。是的,這意味著預設情況下它是禁用的。

例子:

driver。implicitly_wait(10)

Selenium Python 中的流利等待

Fluent 等待類似於 Explicit Waits,但在 Selenium 官方文件中仍將它們分類為不同的等待型別。為什麼文件將它們列為兩種不同的型別?對於顯式等待,他們避免使用諸如 poll_frequency 和ignore_exceptions 之類的非強制性函式引數(即,較少專門使用,較少控制WebDriverWait 類的內部功能)。

在文件中,他們演示了在 Fluent 等待下使用這兩個引數來更好地控制應該忽略哪些異常以及驅動程式應該多久輪詢 DOM。簡而言之,流暢的等待是對顯式等待的更清晰的使用。

例子:

WebDriverWait(driver, 7, poll_frequency=5)。until(EC。alert_is_present(), ‘Timed out waiting for simple alert to appear’)

演示:Selenium 等待頁面載入

現在考慮一個簡單的示例,演示如何使用 Selenium 等待來確保頁面載入。下面的 HTML 指令碼將用於演示:

<!DOCTYPE html>

Click the button to make a BUTTON element with text。

The button element gets created after 3 seconds

執行後,頁面顯示如下:

在 Python 中使用 Selenium 等待頁面載入「教程」

現在,當您嘗試單擊按鈕時,嘗試一下:

單擊預先存在的按鈕三秒鐘後,將建立一個“CLICK ME”按鈕。

在 Python 中使用 Selenium 等待頁面載入「教程」

載入按鈕後兩秒鐘後會顯示警報。

在 Python 中使用 Selenium 等待頁面載入「教程」

這隻有在 Selenium wait 的幫助下才有可能。這導致 CLICK ME 按鈕僅在單擊 Try it 按鈕三秒後加載,並且警報框分別在其兩秒後出現。

在接下來的部分中,我們將展示如何在與這些 WebElement 互動時等待(即,使用 Python Selenium Wait 的按鈕和警報框)。我們還將展示輪詢 DOM 和執行命令的各個方法所花費的時間。

如何使用 Python 在 Selenium 中實現顯式等待和流暢等待

考慮以下使用上述網頁實現 Selenium 等待頁面載入的實現。

import unittestfrom selenium import webdriverfrom selenium。webdriver。common。by import Byfrom selenium。webdriver。support。ui import WebDriverWaitfrom selenium。webdriver。common。action_chains import ActionChainsfrom selenium。webdriver。support import expected_conditions as ECimport timefrom datetime import datetime class DragTest(unittest。TestCase): def setUp(self): # configuration to test in the cloud using lambdaTest username = “your user name” accessToken = “Your access token” gridUrl = “hub。lambdatest。com/wd/hub” desired_cap = { ‘platform’ : “win10”, ‘browserName’ : “chrome”, ‘version’ : “67。0”, “resolution”: “1024x768”, “name”: “LambdaTest python selenium wait testing automation”, “build”: “LambdaTest python selenium wait testing automation”, “network”: True, “video”: True, “visual”: True, “console”: True, } url = “https://”+username+“:”+accessToken+“@”+gridUrl print(“Initiating remote driver on platform: ”+desired_cap[“platform”]+“ browser: ”+desired_cap[“browserName”]+“ version: ”+desired_cap[“version”]) self。driver = webdriver。Remote( desired_capabilities=desired_cap, command_executor= url ) # self。driver = webdriver。Firefox() def test_selenium_wait(self): driver = self。driver driver。maximize_window() # printing time to demonstrate waits pageLoadClock = datetime。now() current_time = pageLoadClock。strftime(“%H:%M:%S”) print(“Time before starting page load =”, current_time) driver。get(‘https://pynishant。github。io/Selenium-python-waits。html’) pageLoadedClock = datetime。now() current_time_after_page_loaded = pageLoadedClock。strftime(“%H:%M:%S”) print(“Time after page load and before clicking the Try it button=”, current_time_after_page_loaded) driver。find_element(By。XPATH, ‘//button[text()=“Try it”]’)。click() # this is scripted to FAIL try: driver。find_element(By。XPATH, ‘//button[text()=“CLICK ME”]’)。click() except Exception as e: ExceptionClock = datetime。now() current_time_Click_me_failed = ExceptionClock。strftime(“%H:%M:%S”) print(“\nTime when click me was attempted to interact with but failed=”, current_time_Click_me_failed) print(“The below exception occured because we didn‘t wait for the element ’button‘ to be available before interaction。”) print(e) # code to use explicit wait for CLICK ME button try: WebDriverClock = datetime。now() current_time_webdriver = WebDriverClock。strftime(“%H:%M:%S”) print(“\nTime before waiting for CLICK ME button with webdriver=”, current_time_webdriver) WebDriverWait(driver, 10)。until(EC。presence_of_element_located((By。ID, “waitCreate”))) ButtonFound = datetime。now() current_time_ButtonFound = ButtonFound。strftime(“%H:%M:%S”) print(“Time when Button Found=”, current_time_ButtonFound) print(“This was interacting with Button using Explicit wait。 Now we shall interact with alert using fluent wait。”) except Exception as e: print(e) print(“error in try block”) # Code to use FLUENT wait for ALERT’s presence identification & handling try: alertClock = datetime。now() current_time_alertClock = alertClock。strftime(“%H:%M:%S”) print(“\nTime before waiting for alert with webdriver=”, current_time_alertClock) WebDriverWait(driver, 7, poll_frequency=5)。until(EC。alert_is_present(), ‘Timed out waiting for simple alert to appear’) alertFound = datetime。now() current_time_alertFound = alertFound。strftime(“%H:%M:%S”) print(“Time when Button Found=”, current_time_alertFound) alert = driver。switch_to。alert time。sleep(1) alert。accept() except Exception as e: print(e) def tearDown(self): # closes the driver self。driver。quit() if __name__ == ‘__main__’: unittest。main()

輸出:

以下是 LambdaTest 在基於雲的 Selenium Grid 上執行 Selenium 測試自動化指令碼時的執行輸出:

在 Python 中使用 Selenium 等待頁面載入「教程」

觀察查詢元素所花費的時間。“CLICK ME”按鈕使用 WebDriverWait 的預設 poll_frequency 進行輪詢,即 500ms。儘管我們給出了 10 秒的超時引數,但 CLICK ME 按鈕的存在是在 3 秒內確定的(即,當我們單擊“Try it”按鈕時,它被建立後的時間)。

但是使用 5 秒的 poll_frequency 來輪詢警報的存在。因此,儘管警報僅在 CLICK ME 按鈕建立兩秒鐘後出現,但 Fluent WebDriverWait 需要五秒鐘來識別它的存在。這無疑闡明瞭 poll_frequency 的使用。

快速瀏覽 LambdaTest 平臺上的執行影片表明等待按預期執行。

在 Python 中使用 Selenium 等待頁面載入「教程」

如何使用 Python 在 Selenium 中實現隱式等待

考慮以下使用隱式 Selenium 等待頁面載入的實現。為簡潔起見,我們僅演示了在 Selenium Python 中使用隱式等待來等待 CLICK ME 按鈕。

import unittestfrom selenium import webdriverfrom selenium。webdriver。common。by import Byfrom selenium。webdriver。support。ui import WebDriverWaitfrom selenium。webdriver。common。action_chains import ActionChainsfrom selenium。webdriver。support import expected_conditions as ECimport timefrom datetime import datetime class DragTest(unittest。TestCase): def setUp(self): # configuration to test in the cloud using lambdaTest username = “your user name” accessToken = “Your access token” gridUrl = “hub。lambdatest。com/wd/hub” desired_cap = { ‘platform’: “win10”, ‘browserName’: “firefox”, ‘version’: “67。0”, “resolution”: “1024x768”, “name”: “LambdaTest python selenium wait testing automation”, “build”: “Implicit Wait”, “network”: True, “video”: True, “visual”: True, “console”: True, } url = “https://” + username + “:” + accessToken + “@” + gridUrl print(“Initiating remote driver on platform: ” + desired_cap[“platform”] + “ browser: ” + desired_cap[ “browserName”] + “ version: ” + desired_cap[“version”]) self。driver = webdriver。Remote( desired_capabilities=desired_cap, command_executor=url ) # self。driver = webdriver。Firefox() def test_selenium_wait(self): driver = self。driver driver。maximize_window() # defining condition for implicit waits - we have set 10 seconds driver。implicitly_wait(10) driver。get(‘https://pynishant。github。io/Selenium-python-waits。html’) pageLoadedClock = datetime。now() current_time_after_page_loaded = pageLoadedClock。strftime(“%H:%M:%S”) print(“Time after page load and before clicking the Try it button=”, current_time_after_page_loaded) driver。find_element(By。XPATH, ‘//button[text()=“Try it”]’)。click() # this won‘t FAIL with implicit time set try: # printing time to demonstrate waits pageLoadClock = datetime。now() current_time = pageLoadClock。strftime(“%H:%M:%S”) print(“Time before starting polling for CLICK ME Button =”, current_time) driver。find_element(By。XPATH, ’//button[text()=“CLICK ME”]‘)。click() pageLoadClock = datetime。now() current_time = pageLoadClock。strftime(“%H:%M:%S”) print(“Time after CLICK ME was found =”, current_time) except Exception as e: print(e) def tearDown(self): # closes the driver self。driver。quit() if __name__ == ’__main__‘: unittest。main()

輸出:

觀察第一個 try 塊是如何成功的,在沒有引入任何顯式等待的情況下,WebDriver 等待建立 CLICK ME 按鈕。

在 Python 中使用 Selenium 等待頁面載入「教程」

在 Python 中使用 Selenium 等待頁面載入「教程」

Python 中其他型別的 Selenium 等待

Selenium Python 中還有另外三種等待型別:

執行非同步 JS 指令碼的等待時間 — set_script_timeout(time_to_wait) 用於指定 execute_async_script() 在丟擲錯誤之前完成非同步 JS 指令碼執行的最大等待時間(以秒為單位)。

句法:driver。set_script_timeout(30)

頁面載入時間的等待時間 - set_page_load_timeout(self, time_to_wait) 用於指定頁面在 selenium WebDriver 控制的瀏覽器中完全載入的最大等待時間(以秒為單位)。當您在節流網路條件下執行 Selenium 自動化測試時,這很有用。

句法:set_page_load_timeout(30)

Sleep(time_to_sleep)——這是一個內建的 Python 函式,用於將程式暫停指定的秒數。但是,睡眠的使用不被認為是 Selenium 自動化測試的最佳實踐之一。

句法:Sleep(3000)

Python 中用於 Selenium 等待的 Polling2 庫

您還可以使用 Python 的 polling2 庫來等待 Selenium WebDriver 中的元素。您必須使用以下命令單獨安裝 polling2 庫:

pip install polling2

Python 中 Polling2 庫的示例用法

from selenium import webdriver driver = webdriver。Chrome()driver。get(’http://www。lambdatest。com‘) email_box = polling2。poll(lambda: driver。find_element_by_id(‘useremail’), step=0。5, timeout=7)email_box。send_keys(’email@email。com‘)sleep(2)driver。quit()

結論

在 Python 中使用 Selenium 等待頁面載入「教程」

在這篇部落格中,我們探討了實現 Selenium 等待頁面在 Python 中載入的不同等待。當測試必須在動態載入的 WebElement 上執行時,Selenium 等待將派上用場。Selenium Python 中的 Fluent wait 允許您控制輪詢頻率,在 Explicit wait 中預設設定為 250 ms。請讓我們知道您是如何使用 Selenium 的,並等待 Python 中的頁面載入來處理 WebElements 的動態性。

快樂測試!

Top