前向驅動器方法 - Selenium Python
此技術用於在 Web 瀏覽器的歷史記錄中向前導航,並允許 Selenium 在瀏覽器的歷史記錄頁面中向前移動,執行任何新的導航命令。
Selenium Python 中的前向驅動器方法可以提高自動化測試指令碼的效率和準確性,它允許您快速在之間移動。
設定
Firefox 可執行檔案
從此處下載 Firefox 瀏覽器安裝程式
下載完成後,安裝瀏覽器,一個 exe 檔案將自動放置在C:\Program Files\Mozilla Firefox\firefox.exe中。我們稍後將需要它。
Gecko 驅動程式
Windows 使用者可以從此處下載 gecko 驅動程式。對於其他版本,請參閱發行說明。
解壓縮 zip 檔案並將“geckodriver.exe”檔案放在 C:\ 目錄中。我們稍後將在程式碼中引用它。
Selenium Python 包
我們將使用最新版本的 Selenium Webdriver,因此使用 pip 安裝以下內容:
pip3 install -U selenium pip3 install -U webdriver-manager
演算法
從 Selenium 匯入必要的模組
使用 Options() 函式設定 Firefox 二進位制檔案位置
使用 Firefox() 函式中的 executable_path 引數設定 Firefox 驅動程式路徑
使用 get() 函式啟動 Firefox 驅動程式並開啟第一個網站
使用 forward() 方法導航到第二個網站並列印頁面的標題
示例
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.firefox.options import Options options = Options() # you need to download and install firefox and it will be in the following path options.binary_location = r'C:\Program Files\Mozilla Firefox\firefox.exe' # you need to download and install geckodriver.exe and put it in the same folder as this script driver = webdriver.Firefox(executable_path=r'C:\geckodriver.exe', options=options) # launch driver using the selenium webdriver and open first website driver.get('https://tutorialspoint.tw/selenium/selenium_automation_practice.htm') print(f"Loaded first page. Title of the page is : {driver.title}") # instruct driver using the selenium webdriver to open the second website driver.get('https://tutorialspoint.tw/python3/index.htm') # step one step forward browser history driver.forward() print(f"Loaded second page. Title of the page is : {driver.title}")
輸出
進度在控制檯中可見
Loaded first page. Title of the page is : Selenium - Automation Practice Form Loaded second page. Title of the page is : Python 3 Tutorial
1. 第一個頁面已載入
2. 第二個頁面已載入
從 Selenium 匯入所需的模組,然後設定 Firefox 瀏覽器的選項。
二進位制檔案位置使用 Firefox 可執行檔案的路徑設定。驅動程式使用 GeckoDriver 可執行檔案的路徑設定,Selenium 需要它與 Firefox 瀏覽器互動。
驅動程式使用 get() 函式啟動以開啟第一個網站,並列印頁面的標題到控制檯。
然後指示驅動程式使用 get() 函式導航到第二個網站。
forward() 方法跳到下一頁。
結論
Selenium Python 前向驅動器方法是一種強大的方法,可以顯著提高自動化測試指令碼的效率和準確性。您可以利用 Selenium WebDriver API 提供的“forward()”方法輕鬆地在瀏覽器的歷史記錄中前進,而無需發出新的導航命令。這可以加快測試指令碼的整體效能並節省您的時間。本博文中討論了在 Selenium Python 中使用前向驅動器方法的優勢,以及有關如何將其整合到您的測試指令碼中的詳細說明。