0
0
Selenium-pythonHow-ToBeginner ยท 3 min read

How to Accept Alert in Selenium: Simple Guide

To accept an alert in Selenium, switch to the alert using driver.switchTo().alert() and then call accept() on it. This will click the OK button on the alert popup and allow your test to continue.
๐Ÿ“

Syntax

The basic syntax to accept an alert in Selenium is:

  • driver.switchTo().alert(): Switches the WebDriver focus to the alert popup.
  • accept(): Clicks the OK button on the alert to accept it.
java
driver.switchTo().alert().accept();
๐Ÿ’ป

Example

This example shows how to open a webpage that triggers an alert, switch to the alert, accept it, and then continue with the test.

java
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class AcceptAlertExample {
    public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();

        driver.get("https://the-internet.herokuapp.com/javascript_alerts");

        // Click button that triggers alert
        driver.findElement(By.xpath("//button[text()='Click for JS Alert']")).click();

        // Switch to alert
        Alert alert = driver.switchTo().alert();

        // Accept the alert
        alert.accept();

        // Verify result text
        String result = driver.findElement(By.id("result")).getText();
        System.out.println("Result text: " + result);

        driver.quit();
    }
}
Output
Result text: You successfully clicked an alert
โš ๏ธ

Common Pitfalls

  • Trying to accept an alert before it appears causes NoAlertPresentException.
  • Not switching to the alert before calling accept() will fail.
  • Ignoring alerts can block test execution.

Always wait or ensure the alert is present before accepting.

java
/* Wrong way: Not switching to alert */
driver.accept(); // This will cause error

/* Right way: Switch then accept */
driver.switchTo().alert().accept();
๐Ÿ“Š

Quick Reference

ActionCode Snippet
Switch to alertdriver.switchTo().alert()
Accept alertdriver.switchTo().alert().accept()
Dismiss alertdriver.switchTo().alert().dismiss()
Get alert textdriver.switchTo().alert().getText()
Send keys to alertdriver.switchTo().alert().sendKeys("text")
โœ…

Key Takeaways

Always switch to the alert before accepting it using driver.switchTo().alert().
Use accept() to click OK on the alert and continue test execution.
Wait for the alert to appear to avoid NoAlertPresentException errors.
Ignoring alerts can block your Selenium tests from running smoothly.
Use dismiss() if you want to cancel the alert instead of accepting it.