Selenium WebDriver with Java: Can't accept ale

2019-01-25 23:14发布

问题:

When recording in selenium IDE I can click the "OK" button in a popup, and expected to be able to click it using

driver.findElement(By.linkText("OK")).click();

but this was not the case.

Similarly this doesn't work.

driver.switchTo().alert().accept();

Selenium throws a NoAlertPresent exception. If what's popping up is not an alert, then what is it? And how do I click yes!

回答1:

in such case I'd prefer to check(verify) the alert presence on the page and then if is present - accept it. It be somthing like:

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;

 }

here you can get details Also do not forget about debug step by step.

Hope this helps you.



回答2:

if you are using latest version of webdriver, infact anything above 2.20 then

driver.switchTo().alert().accept();

should work provided the alert is a javascript alert similar to the one we get when we click

alert demo OR confirm pop-up demo

Updated

here this code will help you accept the alert

driver = new FirefoxDriver();
String baseUrl = "http://www.w3schools.com/js/tryit.asp?filename=tryjs_alert";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
driver.switchTo().frame(0);
driver.findElement(By.cssSelector("input[type=\"button\"]")).click();
driver.switchTo().alert().accept();


回答3:

It could be anything. You should be telling us that.

If it is a Java Script alert then, this should work

driver.switchTo().alert().accept();

At the very least you could try sending enter/return key stroke, if the "OK" button is autoselected/highlighted by the web app.

import org.openqa.selenium.Keys
WebElement.sendKeys(Keys.RETURN);

Update


It could also be because your alert is not present at the time you are trying to click/accept it. For a quick check put in a sleep of 4-5 seconds and then try driver.switchTo().alert().accept();. Once it is ascertained, then put in a wait for alert present in a try and catch loop (any exception handling).