Selenium NoAlertPresentException - selenium

I'm trying to handle dialog (Ok Cancel type) with selenium WebDriver. So my aim is to click "Ok" button.
Scenario is:
Click button for invoking dialog
button.click();
Try to accept
webDriver.switchTo().alert().accept();
But I'm always getting NoAlertPresentException and seeing that dialog closes almost immediately.
It seems to me that Selenium automatically closes dialog and when I want to accept, there is nothing to accept.
I'm sorry for my bad English.

The usual cause of this issue is that Selenium is too quick and tries to accept an alert that has not yet been opened by the browser. This can be simply fixed by an explicit wait:
button.click();
WebDriverWait wait = new WebDriverWait(driver, 5);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.accept();

Step 1:
public boolean isAlertPresent(){
boolean foundAlert = false;
WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
try {
wait.until(ExpectedConditions.alertIsPresent());
foundAlert = true;
System.out.println("isAlertPresent : " +foundAlert);
} catch (TimeoutException eTO) {
foundAlert = false;
System.out.println("isAlertPresent : " +foundAlert);
}
return foundAlert;
}
Step 2:
public boolean tocheck_POP_Dialog()
{ Alert alert;
try
{
alert=driver.switchTo().alert();
}
catch(NoSuchElementException elementException)
{
return false;
}
alert.accept(); //Close Alert popup
return true;
}
Step 3 :
if(dummyPage.isAlertPresent())
{
dummyPage.tocheck_POP_Dialog();
}

public boolean isAlertPresent(){
try{
Alert a = new WebDriverWait(driver, 10).until(ExpectedConditions.alertIsPresent());
if(a!=null){
System.out.println("Alert is present");
driver.switchTo().alert().accept();
return true;
}else{
throw new Throwable();
}
}
catch (Throwable e) {
System.err.println("Alert isn't present!!");
return false;
}
}
Use explicit wait to check the alert and then do the operation. This might help you. :)

Generally it happens because Selenium commands run too quick and it tries to close the alert before it is open. Hence, adding a delay after click event should resolve the issue. Also, if you are using Safari browser for your test, there is some issue with SafariDriver in handling alerts. SafariDriver cannot handle alerts should provide you more details.

Some additional info. for future readers of this thread:
If this exception persists even after the wait aspect is addressed, please check if the following sequence of steps is effective in the test script:
the underlying Html page's DOM is queried/parsed for some purpose (e.g. to look for Form errors)
(before the) driver.switch_to.alert is attempted
When an Alert is shown over an Html page, if the Alert is overlooked and the DOM underlying the Html page is queried first, the Webdriver appears to loose track of the Alert & causes the Exception.
This was observed with: geckodriver 0.21.0, Firefox 66.0b10 (64-bit) ; python 3.6.1 Selenium driver 3.14 (for Python).
Performing (2) before (1) was found to resolve the issue.

Related

How to handle external popup using selenium

In my project, there has one advertisement provider who shows us pop up advertisement but Problem is this pop-up will come it's not fixed.Sometimes add not show sometimes comes this pop up after 1 minute and interrupts my test case.
I write a code for close this popup but it's not a perfect solution I think..If anyone can help?
boolean Imclose = wd.findElement(By.xpath(".//*[#class='IM_overlay_close_container IM_overlay_close_button']")).isDisplayed();
if (Imclose == true) {
wd.findElement(By.xpath(".//*[#class='IM_overlay_close_container IM_overlay_close_button']")).click();
}
Try these code, to handle the unwanted pop up page. I have provided 180 seconds of wait. Then Click on close button inside the advertisement pop up page.
After click on advertisement pop up page, another window is getting open, So I have to redirect to my main window, then only further code will execute.
driver.get("https://www.rentbyowner.com/usa");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
try
{
WebDriverWait wait = new WebDriverWait(driver, 180);
wait.until(ExpectedConditions.visibilityOf(driver.findElement(By.xpath("//div[contains(#class,'IM_overlay_foreground')]"))));
driver.findElement(By.xpath("//div[contains(#class,'IM_overlay_foreground')]//span[#class='IM_close_text']")).click();
try
{
String winHandleBefore = driver.getWindowHandle();
for(String winHandle : driver.getWindowHandles())
{
driver.switchTo().window(winHandle);
//driver.switchTo().window(winHandle).close();
}
driver.switchTo().window(winHandleBefore);
//Verify purpose written code, weather my driver is getting move to parent window or not.
WebDriverWait element = new WebDriverWait(driver, 10);
element.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.id("top_k_search"))));
driver.findElement(By.id("top_k_search")).clear();
System.out.println("Try block");
}
catch(Exception a)
{
System.out.println("Inner Catch");
}
}
catch(Exception e)
{
System.out.println("Element not present");
//Provide your code here..
}
I observed that this is a normal pop-up overlay over the webpage and not an alert and it appears almost within 60 seconds. So, the below code might just work for you.
//Waiting for the Popup to appear
WebDriverWait wait = new WebDriverWait(driver,60);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[contains(#class,'IM_overlay_foreground')]")));
//Clicking on the 'Close' text to close the popup.
driver.findElement(By.xpath("//div[contains(#class,'IM_overlay_foreground')]//span[#class='IM_close_text']")).click();
NOTE: You can increase the time from 60 to 90, in case it appears to take longer. Thing is, whenever the popup appears within the timeframe set, it is handled(as in Closed).
Actually it is coming after 30-50 seconds so you have to wait and then click on close button.
System.setProperty("webdriver.chrome.driver", "E:\\software and tools\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.rentbyowner.com/usa");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
WebElement ad=driver.findElement(By.xpath(".//*[#id='IM_target_overlay']/div/div/div/div[1]/a/div"));
WebDriverWait wait= new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOf(ad));
ad.click();
Refer this link for more information:
Handling Alerts in Selenium Webdriver

Verify that authentication browser popup exists

I have a list of sites and some sites show an authentification window when the site is opened, I need to know what sites show this authentication popup, and which are not.
I'm trying to verify that authentication browser popup shows after page open. But when I use:
Alert alert = driver.switchTo().alert();
alert.accept();
I get an error:
no alert open(Session info: chrome=59.0.3071.115)(Driver info: chromedriver=2.30.477691(6ee44a7247c639c0703f291d320bdf05c1531b57),platform=Linux 4.4.0-83-generic x86_64) (WARNING: The server did not provide any stacktrace information)
Of course, an authentication window appears on the site. enter image description here
One more thing, I don't need authorize on this site, I just need to make sure, that the window appeared.
You can create/modify the method isAlertPresent as given below and try it. It may help you.
First confirm with below method if the alert present
public boolean isAlertPresent() {
try{
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.alertIsPresent());
return true;
}
catch (NoAlertPresentException noAlert) {
return false;
}
catch (TimeoutException timeOutEx){
return false;
}
}
If above not work then JavascriptExecutor worked for you. Just take care that you should execute it before clicking the event which invoke alert.
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg) { return true; }");
Note :- do not use it after clicking on event which invoke alert confirmation box. Above code by default set the confirmation box as true means you are accepting/click on ok on all confirmation box on that page if invoked
It's an authentication pop-up. You can handle it like below :-
WebDriverWait wait = new WebDriverWait(driver, 10);
Alert alert = wait.until(ExpectedConditions.alertIsPresent());
alert.authenticateUsing(new UserAndPassword(username, password));
OR
driver.get("http://UserName:Password#Example.com");
To Press ESC :-
Use action class
Actions action = new Actions(driver);
action.sendKeys(Keys.ESCAPE).build().perform();
Robot class code :-
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_ESCAPE);
robot.keyRelease(KeyEvent.VK_ESCAPE);
Hope it will help you :)

Facing issues in Alertbox selenium 3.0

After clicking save button a pop will open and i write a code below to do accept but its not working.
`driver.findElement(By.id("save")).click();
Alert succ=driver.switchTo().alert();
System.out.println(succ.getText());
Thread.sleep(2000);
succ.accept();`
Need Help please.
The behavior of selenium varies according to browser, In some case the actions done in Firefox browser like form filling actions or clicking the button is faster then Chrome browser so your script well executed in chrome but throw error in Firefox so you need to add some pause to make them perform well.
So in your case after clicking the save button selenium executing the command too fast so skip to switch on alert and accept so add some wait using Thread.sleep(); to make pause
driver.findElement(By.id("save")).click();
Thread.sleep(2000);
Alert succ=driver.switchTo().alert();
System.out.println(succ.getText());
Thread.sleep(2000);
succ.accept();
Note : It is not recommended to use Thread.sleep(); instead use implicit or explicitwait conditions
WebDriverWait wait = new WebDriverWait(driver, 60);
wait.until(ExpectedConditions.alertIsPresent());
Try this:
driver.findElement(By.id("save")).click();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(driver.switchTo().alert().getText());
driver.switchTo().alert().accept();

Testing a negative flow in Selenium webdriver

Issue:- webelement (Button) isdisplayed() doesn't works for negative scenarios
Requirement:- I need to fail a test flow in case a button is not displayed on the screen and if its present, then proceed with the flow
Code:-
if (driver.findElement(By.id("button")).isDisplayed() == false) {
System.out.println("The Button isn't present. Exiting!!");
driver.findElement(By.linkText("Logout")).click();
}
else
{
//Proceed with the positive flow
}
In above code, if the button is not present at all on the screen, the test should fail (if statement should be executed, but it's not)
As TestAutomationEngr has mentioned, make sure there is only one type of such button on the page...
one more way you could test for negative flow in webdriver is by using a try and catch..
In your case,
boolean buttonFound=false;
try
{
new WebDriverWait(driver,10).until(ExpectedConditions.visibilityOfElementLocated(By.id("button")));
buttonFound=true;
}catch(Exception e)
{
System.out.println("The Button isn't present. Exiting!!");
driver.findElement(By.linkText("Logout")).click();
}
if(buttonFound)
{
//positive flow
}
here it'l wait for 10 secs for visibility of element,
if found, buttonFound is set to true,hence positive flow is executed
if not found, the message in catch clause will be displayed and logout link will be clicked
In fact it is not required to logout in case an exception is thrown because when the driver is closed this session will be lost. The following code will fail the test in case the element is not present or it is not enabled.
WebElement elem = driver.findElement(By.id("button"));
Assert.assertTrue(elem.isEnabled());
At the end you just need to close the driver in the test teardown the
driver.close()
You can use the FindElements.Count approach.
Like this:
public bool IsElementDisplayed(IWebDriver driver, By element)
{
if (driver.FindElements(element).Count > 0)
{
if (driver.FindElement(element).Displayed)
return true;
else
return false;
}
else
{
return false;
}
}
Hope it helps.

Selenium Webdriver - how to close the first pop up window and go to the actual page

I'm trying to automate the webpage "http://www.quikr.com",when I open this you will get a pop up window first saying "Please Choose Your Location" then after closing it , I can see the main page of quikr.
I tried closing that Popup page by automation ,but not able to do
Tried using xpath
driver.findElement(By.xpath("//*[#id='csclose']/strong")).click();
Tried using className
driver.findElement(By.className("cs-close cs-close-v2")).click();
Tried using id
driver.findElement(By.id("csclose")).click();
Please help me with this
to close multiple popups in webdriver and switch to parent window
String parent = driver.getWindowHandle();
Set<String> pops=driver.getWindowHandles();
{
Iterator<String> it =pops.iterator();
while (it.hasNext()) {
String popupHandle=it.next().toString();
if(!popupHandle.contains(parent))
{
driver.switchTo().window(popupHandle);
System.out.println("Popu Up Title: "+ driver.switchTo().window(popupHandle).getTitle());
driver.close();
The Following Code Works for Me to Handle Pop Up/ Alerts in Selenium Webdriver
Just Copy Paste this Code After the Event which is triggering the Pop up/Alert i.e after clicking on save.
if(driver.switchTo().alert() != null)
{
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
alert.dismiss(); // alert.accept();
}
in your case you try to run this code at starting of the code bcz it will directly close the pop up
Since this is a JavaScript modal, when the page finishes loading the JavaScript code could still be running. The solution is to wait until the button to close the modal be displayed, close it and then follow with your test. Like this:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementIsVisible(By.Id("csclose")));
driver.FindElement(By.Id("csclose")).Click();
Tested myself and works fine.
Hope it helps.
i have tried it in ruby and this one works
see if this can help you in any way :)
require 'selenium-webdriver'
require 'test/unit'
require 'rubygems'
class Tclogin < Test::Unit::TestCase #------------ define a class----------------
def setup
##driver = Selenium::WebDriver.for :firefox
##driver.navigate.to "http://www.quikr.com" #---- call url----
##wait = Selenium::WebDriver::Wait.new(:timeout => 60) # seconds #----define wait------
end
def test_login
##driver.find_element(:css, "strong").click
end
end
you can also use follwing xpath
##driver.find_element(:xpath, "//a[#id='csclose']/strong").click
public void closePopup() throws Exception {
WebDriver driver = new InternetExplorerDriver();
driver.get("http://www.quikr.com/");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("csclose"))).click();
System.out.println("Successfully closed the start Popup");
}
Try driver.findElement(By.Id("csclose")).click(); I hope that will help
Simple pressing Alt + F4 buttons worked for me, e.g.:
driver.findElement(By.cssSelector("html body div div img")).sendKeys(Keys.chord(Keys.ALT, Keys.F4));