I am using a Chrome Driver and trying to test a webpage.
Normally it runs fine, but sometimes I get exceptions:
org.openqa.selenium.UnhandledAlertException: unexpected alert open
(Session info: chrome=38.0.2125.111)
(Driver info: chromedriver=2.9.248315,platform=Windows NT 6.1 x86) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 16 milliseconds: null
Build info: version: '2.42.2', revision: '6a6995d', time: '2014-06-03 17:42:30'
System info: host: 'Casper-PC', ip: '10.0.0.4', os.name: 'Windows 7', os.arch: 'x86', os.version: '6.1', java.version: '1.8.0_25'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Then I tried to handle the alert:
Alert alt = driver.switchTo().alert();
alt.accept();
But this time I received:
org.openqa.selenium.NoAlertPresentException
I am attaching the screenshots of the alert:
I am not able to figure out what to do now. The problem is that I do not always receive this exception. And when it occurs, the test fails.
I had this problem too. It was due to the default behaviour of the driver when it encounters an alert. The default behaviour was set to "ACCEPT", thus the alert was closed automatically, and the switchTo().alert() couldn't find it.
The solution is to modify the default behaviour of the driver ("IGNORE"), so that it doesn't close the alert:
DesiredCapabilities dc = new DesiredCapabilities();
dc.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
d = new FirefoxDriver(dc);
Then you can handle it:
try {
click(myButton);
} catch (UnhandledAlertException f) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert data: " + alertText);
alert.accept();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
You can use Wait functionality in Selenium WebDriver to wait for an alert, and accept it once it is available.
In C# -
public static void HandleAlert(IWebDriver driver, WebDriverWait wait)
{
if (wait == null)
{
wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
}
try
{
IAlert alert = wait.Until(drv => {
try
{
return drv.SwitchTo().Alert();
}
catch (NoAlertPresentException)
{
return null;
}
});
alert.Accept();
}
catch (WebDriverTimeoutException) { /* Ignore */ }
}
Its equivalent in Java -
public static void HandleAlert(WebDriver driver, WebDriverWait wait) {
if (wait == null) {
wait = new WebDriverWait(driver, 5);
}
try {
Alert alert = wait.Until(new ExpectedCondition<Alert>{
return new ExpectedCondition<Alert>() {
#Override
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch (NoAlertPresentException e) {
return null;
}
}
}
});
alert.Accept();
} catch (WebDriverTimeoutException) { /* Ignore */ }
}
It will wait for 5 seconds until an alert is present, you can catch the exception and deal with it, if the expected alert is not available.
Is your switch to alert within a try/catch block? You may also want to add a wait timeout to see if the alert shows up after a certain delay
try {
// Add a wait timeout before this statement to make
// sure you are not checking for the alert too soon.
Alert alt = driver.switchTo().alert();
alt.accept();
} catch(NoAlertPresentException noe) {
// No alert found on page, proceed with test.
}
UnhandledAlertException
is thrown when it encounters an unhanded alert box popping out. You need to set your code to act normally unless an alert box scenario is found. This overcomes your problem.
try {
System.out.println("Opening page: {}");
driver.get({Add URL});
System.out.println("Wait a bit for the page to render");
TimeUnit.SECONDS.sleep(5);
System.out.println("Taking Screenshot");
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "C:\\images";
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
} catch (UnhandledAlertException ex) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("ERROR: (ALERT BOX DETECTED) - ALERT MSG : " + alertText);
alert.accept();
File outputFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
String imageDetails = "C:\\Users";
File screenShot = new File(imageDetails).getAbsoluteFile();
FileUtils.copyFile(outputFile, screenShot);
System.out.println("Screenshot saved: {}" + imageDetails);
driver.close();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
After click event add this below code to handle
try{
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
catch (org.openqa.selenium.UnhandledAlertException e) {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText().trim();
System.out.println("Alert data: "+ alertText);
alert.dismiss();}
... do other things
driver.close();
DesiredCapabilities firefox = DesiredCapabilities.firefox();
firefox.setCapability(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.IGNORE);
You can use UnexpectedAlertBehaviour.ACCEPT or UnexpectedAlertBehaviour.DISMISS
I was facing the same issue and I made this below changes.
try {
click(myButton);
} catch (UnhandledAlertException f) {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
System.out.println("Alert data: " + alertText);
alert.accept();
} catch (NoAlertPresentException e) {
e.printStackTrace();
}
}
It worked amazingly.
I tried this below code, it perfectly worked for me (Chrome)
try{
System.out.println("Waiting for Alert");
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.alertIsPresent()).dismiss();
System.out.println("Alert Displayed");
}
catch (Exception e){
System.out.println("Alert not Displayed");
}
You can try this snippet:
public void acceptAlertIfAvailable(long timeout)
{
long waitForAlert= System.currentTimeMillis() + timeout;
boolean boolFound = false;
do
{
try
{
Alert alert = this.driver.switchTo().alert();
if (alert != null)
{
alert.accept();
boolFound = true;
}
}
catch (NoAlertPresentException ex) {}
} while ((System.currentTimeMillis() < waitForAlert) && (!boolFound));
}
Following is working for me
private void acceptSecurityAlert() {
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver).withTimeout(10, TimeUnit.SECONDS)
.pollingEvery(3, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
Alert alert = wait.until(new Function<WebDriver, Alert>() {
public Alert apply(WebDriver driver) {
try {
return driver.switchTo().alert();
} catch(NoAlertPresentException e) {
return null;
}
}
});
alert.accept();
}
The below code will help to handle unexpected alerts in selenium
try{
} catch (Exception e) {
if(e.toString().contains("org.openqa.selenium.UnhandledAlertException"))
{
Alert alert = getDriver().switchTo().alert();
alert.accept();
}
}
Related
My Wait() method works in 'Chrome' & 'Firefox' but not in 'IE', any ideas?
I have tried using IEDriverServer.exe both the 32bit and the 64bit(Send keys acts slow), but the following method still dosnt click on the intended target.
Please note: I know the locators are fine as listed above works in both Chrome and firefox.
public void waitAndClickFirstDrivingExperiencesOption(WebElement element) throws Exception {
WebDriverWait wait2 = new WebDriverWait(driver, 30);
Base_Page basePage = new Base_Page(driver);
try {
System.out.println(basePage.browser_type);
Boolean elementPresent = wait2.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
if (elementPresent == true) {
if (!this.browser_type.equals("firefox")) {
// Provide a slight timeout before clicking on the element
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
basePage.actionMoveAndClick(element);
} else {
Thread.sleep(500);
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
element.click();
}
}
System.out.println("Clicked on the first supercars link, using locator: " + element.toString());
} catch (StaleElementReferenceException elementUpdated) {
element = this.driver.findElement(By.xpath(".//*[#id='prd_listing']/div/li[1]/a"));
Boolean elementPresent = wait2.until(ExpectedConditions.elementToBeClickable(element)).isEnabled();
if (elementPresent == true) {
if (!this.browser_type.equals("firefox")) {
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
basePage.actionMoveAndClick(element);
} else {
Thread.sleep(500);
basePage.scrollToElementByLocator(element);
Thread.sleep(1000);
element.click();
}
}
System.out.println(
"Clicked on the first supercars link (Stale Exception), using locator: " + element.toString());
} catch (Exception e) {
System.out.println("Exception! - could not click on the first supercars link, Exception: " + e.toString());
throw (e);
} finally {
}
This is the code i have tried to handle window but the url for opens in the tab of google.
System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");
WebDriver driver =new ChromeDriver();
driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
try {
Thread.sleep(3000);
for(String windowHandle:driver.getWindowHandles()) {
driver.switchTo().window(windowHandle);
}
driver.get("http://fb.com");
} catch (Exception e) {
System.out.println(e);
}
In the iteration over the window handles you are switching to both of them. The last switch returns the focus to the first window and the link is getting opened there.
You should do the switch only to the new window
System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");
WebDriver driver = new ChromeDriver();
driver.get("http://google.com");
String firstWindowHandle = driver.getWindowHandle();
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
try {
Thread.sleep(3000);
for(String windowHandle : driver.getWindowHandles()) {
if (!windowHandle.equals(firstWindowHandle)) {
driver.switchTo().window(windowHandle);
}
}
driver.get("http://fb.com");
} catch (Exception e) {
System.out.println(e);
}
Driver is opening in same window, because for loop is switching old handle
Code probably should look like this below
System.setProperty("webdriver.chrome.driver", "/home/ish/chromedriver");
WebDriver driver =new ChromeDriver();
driver.get("http://google.com");
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL+"n");
String currentHandle = driver.getWindowHandle();
try {
Thread.sleep(3000);
for(String windowHandle:driver.getWindowHandles()) {
if(!currentHandle.equals(windowHandle)){
driver.switchTo().window(windowHandle);
break;
}
}
driver.get("http://fb.com");
} catch (Exception e) {
System.out.println(e);
}
I am trying to login and search records based on date selected from a calendar. I have used try catch exception after each step. I need to replace try catch with WebDriverWait. But the problem is that I have fields on the page which are getting identified by id or XPath. So I am not getting a way out how to implement WebDriverWait instead of try catch. Can anyone help me out? Below is my code structure with details.
public class Login {
public static WebDriver driver;
String username = "username";
String password = "password";
String baseurl = "http://mybusiness.com/login.aspx";
public class Details {
#Test(priority = 0)
public void loginpage() {
//WebDriver driver = new FirefoxDriver();
System.setProperty("webdriver.chrome.driver","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("--test-type");
options.addArguments("--disable-extensions");
capabilities.setCapability("chrome.binary","D:\\From H\\Selenium Package\\ChromeDriver\\chromedriver_win32\\chromedriver.exe");
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
driver = new ChromeDriver(capabilities);
driver.manage().deleteAllCookies();
driver.manage().window().maximize();
driver.get(baseurl);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement password = driver.findElement(By.id("Password"));
password.sendKeys(password);
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement button = driver.findElement(By.id("ButtonClick"));
button.click();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
// Selecting a date from date picker
#Test(priority = 1)
public void RecordSearch() {
WebElement calendar = driver.findElement(By.id("CalendarId"));
calendar.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement month = driver.findElement(By.xpath("XPath"));
month.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement day = driver.findElement(By.xpath("XPath"));
day.click();
try {
Thread.sleep(5000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
WebElement submit = driver.findElement(By.id("Submit"));
submit.click();
try {
Thread.sleep(10000); // 1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
driver.close();
}
I would have thought you'd be better off adding an implicit wait, e.g. once you've setup your driver object add the following line:
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
A simple example would take your code
try
{
Thread.sleep(10000); // 1000 milliseconds is one second.
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
}
WebElement username = driver.findElement(By.id("UserName"));
username.sendKeys(username);
and change it to
String username = "username123";
WebDriverWait wait = new WebDriverWait(driver, 10); // 10 seconds
WebElement usernameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("UserName")));
usernameField.sendKeys(username);
Once you have defined wait, you can reuse it over and over and it will have the same attributes, e.g. 10 sec wait time.
String password = "abc123";
WebElement passwordField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Password")));
passwordField.sendKeys(password);
NOTE: I noticed that you were using username.sendKeys(username);. I'm assuming/hoping this isn't actual code since .sendKeys() takes a String and you have username defined as a WebElement. I fixed it in my code and named the two differently.
There is WebDriverWait functionality in selenium, you can set explicit wait. You are using selenium webdriver, then it is far better to use WebDriverWait for waiting purpose to element. follow below code
protected WebElement waitForPresent(final String locator, long timeout) {
WebDriverWait wait = new WebDriverWait(driver, timeout);
WebElement ele = null;
try {
ele = wait.until(ExpectedConditions
.presenceOfElementLocated(locator));
} catch (Exception e) {
throw e;
}
return ele;
}
protected WebElement waitForNotPresent(final String locator, long timeout) {
timeout = timeout * 1000;
long startTime = System.currentTimeMillis();
WebElement ele = null;
while ((System.currentTimeMillis() - startTime) < timeout) {
try {
ele = findElement(locator);
Thread.sleep(1000);
} catch (Exception e) {
break;
}
}
return ele;
}
Whenever you require wait for element present, call waitForPresent method with expected parameters.
If you explore little, you can find different types of WebDriverWait. One of the most common is WebDriver.wait(timeinmilliseconds).
and for example, others are,
webDriver.waituntil (Expectedconditions)...
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver driver) {
WebElement button = driver.findElement(By.className("sel"));
String enabled = button.getText();
return enabled.contains(city);
}
});
or for example
wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("froexample_username_txtbox")));
PS : define private final WebDriverWait wait;
It may be more useful if you are not sure about implict timewait value.(be being specific about events and results)
I have code something like this
WebDriver driver = new FirefoxDriver();
driver.get(something URL);
WebDriverWait waiting = new WebDriverWait(driver, 10, 1000);
WebElement element = waiting.until(ExpectedConditions.presenceOfElementLocated(By.id(my_id)));//problem is here
But then i try to find element on my page, WebDriverWait waiting until the page has completely loaded and then starts searching.
If I'm trying something like this
WebDriverWait waiting = new WebDriverWait(driver, 10, 2700);
driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS);
WebElement element;
try {
driver.get(something_url);
} catch (TimeoutException e) {
((JavascriptExecutor) driver).executeScript("window.stop();");
}finally {
element = waiting.until(ExpectedConditions.presenceOfElementLocated(By.id(my_id)));
}
It works, but if I go on like this
element.click();//go to another page
On this line doesn't throw a timeout exception, I have to wait for the full page load.
How to be in this situation ?
Solution is to wait for ajax refresh to complete on this page:
public void waitForAjaxRefresh() {
System.out.println("Waiting for Ajax Refresh");
try {
WebDriverWait wait = new WebDriverWait(driver,35);
final JavascriptExecutor javascript = (JavascriptExecutor) (driver instanceof JavascriptExecutor ? driver
: null);
wait.until(new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver d) {
boolean outcome = Boolean.parseBoolean(javascript
.executeScript("return jQuery.active == 0")
.toString());
return outcome;
}
});
} catch (TimeoutException ex) {
throw new TimeoutException("Timed out after "
+ 35
+ " seconds while waiting for Ajax to complete.");
} catch (WebDriverException e) {
System.out.println("JQuery libraries are not present on page "
+ driver.getCurrentUrl() + " - "
+ driver.getTitle());
}
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
selenium 2.4.0, how to check for presence of an alert
I am using the following code to close the alert window :
Alert alert3 = driver.switchTo().alert();
alert3.dismiss();
The alert appears a few seconds after the opening of the main window.
How can I wait and check if alert appears ?
No default method for waiting for alert.
but, you can write your own method something like this.
waitForAlert(WebDriver driver)
{
int i=0;
while(i++<5)
{
try
{
Alert alert = driver.switchTo().alert();
break;
}
catch(NoAlertPresentException e)
{
Thread.sleep(1000);
continue;
}
}
}
public boolean isAlertPresent() {
boolean presentFlag = false;
try {
// Check the presence of alert
Alert alert = driver.switchTo().alert();
// Alert present; set the flag
presentFlag = true;
// if present consume the alert
alert.accept();
} catch (NoAlertPresentException ex) {
// Alert not present
ex.printStackTrace();
}
return presentFlag;
}