Alert doesn't close using Selenium WebDriver with Google Chrome.

前端 未结 2 1311
-上瘾入骨i
-上瘾入骨i 2021-01-24 15:16

I have the following Selenium script for opening alert on rediff.com:

public class TestC {
    public static void main(S         


        
2条回答
  •  后悔当初
    2021-01-24 16:09

    I'm pretty sure your problem is a very common one, that's why i never advise using Thread.sleep(), since it does not guarantee the code will run only when the Alert shows up, also it may add up time to your tests even when the alert is shown.

    The code below should wait only until some alert is display on the page, and i'd advise you using this one Firefox and IE9 aswell.

    public class TestC {
        public static void main(String[] args) throws InterruptedException, Exception {
            System.setProperty("webdriver.chrome.driver", "driver/chromedriver.exe");
            WebDriver driver = new ChromeDriver();   
            WebDriverWait wait = new WebDriverWait(driver, 5);
    
            driver.get("http://www.rediff.com/");
            driver.findElement(By.xpath("//*[@id='signin_info']/a[1]")).click();
            driver.findElement(By.id("btn_login")).click();
    
            wait.until(ExpectedConditions.alertIsPresent());
    
            Alert alert = driver.switchTo().alert();
            alert.accept();
        }
    }
    

    Mostly all that is done here, is changing Thread.sleep(), for a condition that actually will only move forward on the code as soon a alert() is present in the page. As soon as someone does, it wil switch to it and accept.

    You can find the Javadoc for the whole ExpectedConditions class here.

提交回复
热议问题