Selenium WebDriver with Java: Can't accept alert

前端 未结 3 1566
忘掉有多难
忘掉有多难 2020-12-18 14:58

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\")).cl         


        
相关标签:
3条回答
  • 2020-12-18 15:13

    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.

    0 讨论(0)
  • 2020-12-18 15:16

    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();
    
    0 讨论(0)
  • 2020-12-18 15:25

    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).

    0 讨论(0)
提交回复
热议问题