简体   繁体   中英

Unable to Handle Ajax Pop up in Selenium WebDriver

I'm new in Selenium. I'm trying to make Script in selenium of MacDonald's login and Order.But After login I'm unable to click Continue and any other option please help me.

my code is:--

WebDriver selenium= new FirefoxDriver();
selenium.manage().window().maximize();

String baseurl = "http://www.mcdelivery.co.in/";
selenium.get(baseurl);

Thread.sleep(2000); 
Thread.sleep(5000);

WebElement loginbtn = selenium.findElement(By.id("lnkBtnLogin"));
if(loginbtn.isDisplayed()) {
    loginbtn.click();
}

WebElement username = selenium.findElement(By.id("txtMobileNumber"));
if(username.isDisplayed()) {
    username.clear();
    username.sendKeys("******");
}

WebElement pwd = selenium.findElement(By.id("txtMsgPwd"));
if(pwd.isDisplayed()) {
    pwd.sendKeys("******");
}

WebElement submit = selenium.findElement(By.id("btnSubmit"));
if(submit.isDisplayed()) {
    submit.click(); 
    //Alert aler = selenium.switchTo().alert().accept();
    selenium.switchTo().activeElement();         
}

WebElement conti = selenium.findElement(By.id("btnContinue"));
if(conti.isDisplayed()) {
    conti.click();
}

// selenium.close();

After running this I'm Getting Error

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: 
{"method":"id","selector":"btnContinue"}
Command duration or timeout: 31 milliseconds

Since the Continue button is the part of the pop-up (which takes time to load), you need to give some time to webdriver to detect it. For that purpose, give a timeout using Implicit/Explicit waits .

For above, you can use an Implicit timeout at the top like this;

selenium.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

The above gives a 15 seconds time to the webdriver, each time it tries to locate an element.

Also, in this code,

if(conti.isDisplayed())

{ 

conti.click();

}

for some odd reasons, the Continue button wasn't getting clicked when inside the if ( conti.isDisplayed() ) . So, lose that loop. Just use conti.click(); . It worked when tried!

Hi use some kind of explicit wait after switching to the popup like

         boolean ajaxPopup = new WebDriverWait(driver,10).until(ExpectedConditions
                 .visibilityOfElementLocated(By.id("btnContinue"))) != null;

         Assert.assertTrue(ajaxPopup);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM