Handling alerts in Selenium primarily depends on the Alert interface, which provides methods for managing browser alert pop-ups. Handling alerts typically involves the following steps:
-
Waiting for the alert to appear: First, ensure the alert has been triggered and is visible on the page. You can use
WebDriverWaitwithExpectedConditions.alertIsPresent()to verify its presence. -
Switching to the alert: Using the
driver.switchTo().alert()method transfers control from the webpage to the alert box. -
Interacting with the alert: Once control is switched to the alert, you can use methods provided by the
Alertinterface to interact with it. The primary methods include:accept(): Accepts the alert, equivalent to clicking "OK" or "Yes".dismiss(): Dismisses the alert, equivalent to clicking "Cancel" or "No".getText(): Retrieves the alert text.sendKeys(String stringToSend): Sends text to the alert input field, typically used for input boxes.
Suppose we have a webpage where clicking a button triggers an alert. The following is an example of how to handle this alert using Selenium:
javaimport org.openqa.selenium.Alert; 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; public class AlertHandling { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); WebDriverWait wait = new WebDriverWait(driver, 10); driver.get("http://example.com"); driver.findElement(By.id("trigger-alert-button")).click(); // Assume this is the button that triggers the alert // Wait for the alert to appear wait.until(ExpectedConditions.alertIsPresent()); // Switch to the alert Alert alert = driver.switchTo().alert(); // Get alert text and print System.out.println("Alert text is: " + alert.getText()); // Accept the alert alert.accept(); // Close the browser driver.quit(); } }
These operations ensure that you can effectively control and respond to browser alert pop-ups.