如何使用 Selenium 測試需要身份驗證的頁面?
我們可以使用 Selenium 測試需要身份驗證的頁面。為此,我們必須將使用者的憑據傳送到 URL。實際上,我們同時傳遞附加到 URL 的使用者名稱和密碼。
語法
https://username:password@URL https://admin:admin@the-internet.herokuapp.com/basic_auth
在此處,“admin”是使用者名稱和密碼。
URL – www.the-internet.herokuapp.com/basic_auth
讓我們看看如何接受驗證彈窗。
示例
程式碼實現。
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class TestAuthnPopup{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String t = "admin"; // adding username, password with URL String s = "https://" + t + ":" + t + "@" + "the-internet.herokuapp.com/basic_auth"; driver.get(s); // identify and get text after authentication of popup String m = driver.findElement(By.cssSelector("p")).getText(); System.out.println("Text after pop-up authentication: " + m); driver.quit(); } }
輸出
廣告