For practice use the below alert buttons and validate the proper message.
Handling alerts in Selenium WebDriver involves dealing with pop-up dialogs that appear during automated testing, such as alert, confirmation, and prompt dialogs. These dialogs can interrupt the test execution flow and require specific actions to handle them appropriately. Here's a brief introduction to handling alerts in Selenium WebDriver with a code hint in Java:
// Import necessary Selenium WebDriver classes
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class AlertHandlingExample {
public static void main(String[] args) {
// Set the path to the ChromeDriver executable
System.setProperty("webdriver.chrome.driver", "path_to_chromedriver");
// Instantiate ChromeDriver
WebDriver driver = new ChromeDriver();
// Navigate to a webpage containing an alert
driver.get("https://www.example.com");
// Find the element that triggers the alert (e.g., a button)
driver.findElement(By.id("alertButton")).click();
// Switch to the alert
Alert alert = driver.switchTo().alert();
// Get the text of the alert
String alertText = alert.getText();
System.out.println("Alert Text: " + alertText);
// Perform an action on the alert (e.g., accept/dismiss)
alert.accept(); // To accept the alert
// alert.dismiss(); // To dismiss the alert
// Close the browser
driver.quit();
}
}
Explanation:
import statement imports the necessary Selenium WebDriver classes. System.setProperty() method sets the path to the ChromeDriver executable. WebDriver interface is the root interface for all Selenium WebDriver classes. ChromeDriver class is a concrete implementation of the WebDriver interface, and is used to control Chrome browsers. driver.get() method navigates to a webpage containing an alert. driver.findElement(By.id("alertButton")) method finds the element that triggers the alert (e.g., a button). driver.findElement(By.id("alertButton")).click() method clicks on the element that triggers the alert. driver.switchTo().alert() method switches to the alert. alert.getText() method gets the text of the alert. System.out.println() method prints the text of the alert to the console. alert.accept() method accepts the alert. driver.quit() method closes the browser. The key points are:
import statement imports the necessary Selenium WebDriver classes. System.setProperty() method sets the path to the ChromeDriver executable. WebDriver interface is the root interface for all Selenium WebDriver classes. ChromeDriver class is a concrete implementation of the WebDriver interface, and is used to control Chrome browsers. driver.get() method navigates to a webpage containing an alert. driver.findElement(By.id("alertButton")) method finds the element that triggers the alert (e.g., a button).