How to Handle Alert Pop up in Selenium Webdriver

Here we will see how alert pop up are handled in webdriver.

package beginner_level;

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

public class CodeForAlert {

public static void main(String[] args) throws InterruptedException {
// Open in chrome  browser
System.setProperty(“webdriver.chrome.driver”,”D:\\selenium workspace\\chrome\\new chrome 2\\chromedriver_win32(1)\\chromedriver.exe”);

WebDriver driver = new ChromeDriver();

//Open the railway site – [ http://www.indianrail.gov.in/seat_Avail.html ]
driver.get(“http://www.indianrail.gov.in/seat_Avail.html”);
// Click on the “Get Availability” icon
driver.findElement(By.xpath(“//input[contains(@value,’Get Availability’)]”)).click();
// Check the alert box
Alert a1= driver.switchTo().alert();
// Get the text from alert box
String s = a1.getText();
Thread.sleep(3000);
// Print the text
System.out.println(“Text present in alert box is – ” + a1);
// Click on ok
a1.accept();
// Print the success text after alert is closed
System.out.println(“Alert box is closed now”);

// Close the browser
driver.close();
}

}

2 thoughts on “How to Handle Alert Pop up in Selenium Webdriver

Leave a comment