如何用Selenium WebDriver(Java)测试网站验证弹窗并输出至控制台
Java Selenium Script to Capture and Print Validation Popup Messages
I’ve got you covered! Below are two common scenarios you’ll encounter (native browser alerts and custom modal popups) with complete Java Selenium code to capture those validation messages and output them to your console.
Scenario 1: Native Browser Alert Popups
If your website uses the standard browser alert() function for validation prompts, Selenium’s built-in Alert class makes this super straightforward:
Step-by-Step Code Example
import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.NoAlertPresentException; public class ValidationAlertTest { public static void main(String[] args) { // Initialize ChromeDriver (ensure chromedriver is in your PATH or specify its file path) WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); try { // Navigate to your test website driver.get("your-target-website-url"); // 1. Enter invalid data into form fields (update selectors to match your site) driver.findElement(By.id("user-phone")).sendKeys("123"); // Invalid phone number driver.findElement(By.id("user-age")).sendKeys("abc"); // Non-numeric age // 2. Trigger validation by clicking the save button driver.findElement(By.id("submit-save")).click(); // 3. Switch to the alert and capture its message Alert validationAlert = driver.switchTo().alert(); String alertMessage = validationAlert.getText(); // 4. Print the message to your console System.out.println("Validation Alert Message: " + alertMessage); // 5. Close the alert to continue testing (use dismiss() if it's a confirm popup) validationAlert.accept(); } catch (NoAlertPresentException e) { System.out.println("No alert appeared after submitting invalid data."); e.printStackTrace(); } finally { // Clean up: shut down the driver driver.quit(); } } }
Scenario 2: Custom Modal Popups (Non-Native Alerts)
Most modern websites use custom HTML/CSS modals instead of native alerts. For these, you’ll need to locate the popup element directly and extract its text—plus use explicit waits to make sure the popup loads before you try to access it:
Step-by-Step Code Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.time.Duration; public class CustomModalValidationTest { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.manage().window().maximize(); // Set a 10-second explicit wait (adjust timeout based on your site's load speed) WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); try { driver.get("your-target-website-url"); // Enter invalid form data driver.findElement(By.id("user-email")).sendKeys("not-an-email"); driver.findElement(By.id("user-address")).sendKeys(""); // Empty required field // Trigger save action to show validation driver.findElement(By.id("submit-save")).click(); // Wait for the custom modal to become visible, then grab the message // Update the selector to match your popup's message element (use dev tools to inspect) String modalMessage = wait.until(ExpectedConditions.visibilityOfElementLocated( By.cssSelector(".validation-modal .error-message") )).getText(); // Print the validation message to console System.out.println("Custom Modal Validation Message: " + modalMessage); // Optional: Close the modal to proceed with further test steps driver.findElement(By.cssSelector(".validation-modal .close-btn")).click(); } catch (Exception e) { System.out.println("Failed to capture validation message: " + e.getMessage()); e.printStackTrace(); } finally { driver.quit(); } } }
Key Tips for Your Test:
- Update Selectors: Replace all element IDs/CSS selectors with the actual ones from your website (use your browser’s dev tools to inspect elements).
- Explicit Waits: Always use explicit waits for custom modals—this avoids race conditions where your script tries to access the popup before it loads.
- Error Handling: The try-catch blocks help you debug cases where the popup doesn’t appear as expected (e.g., if your invalid input doesn’t trigger validation).
内容的提问来源于stack exchange,提问作者kjeraska
相关产品推荐
相关产品推荐

