当前位置: 动力学知识库 > 问答 > 编程问答 >

java - I would like to select radio type check-box in my web application through selenium web-driver whenever it is available

问题描述:

I would like to select radio type check-box in my web application through selenium web-driver whenever is it is available

HTML:

<div class="enhanced-checkbox">

<input id="idYes" class="checkbox" type="radio" data-form-message="This is required" required="" value="Y" name="name">

<span></span>

</div>

It work with below web driver code:

if (idYes.isElementPresentAndDisplayed())

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true", idYes.isElementPresentAndDisplayed());

idYes.click();

I also tried: (in this case radio button selected but not ignoring for other scenarios)

if (idYes.isElementPresentAndDisplayed()){

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true", idYes.isElementPresentAndDisplayed());

idYes.click();}

or another try: (in this case radio button not selected)

if (idYes.isElementPresentAndDisplayed()){

((JavascriptExecutor)driver).executeScript("arguments[0].checked = true", idYes.isElementPresentAndDisplayed());

idYes.clickIfElement Present();}

But when above element is not available in different scenarios, then it is failing.

Expected behavior is : If element present select or ignore.

网友答案:

Put your code in try catch block. In catch block, ignore any error occured.

e.g.

try{
WebElement idYes = driver.findElement(By.id("idYes"));
if (idYes.isElementPresentAndDisplayed())
    ((JavascriptExecutor)driver).executeScript("arguments[0].checked = true",idYes.isElementPresentAndDisplayed());

    idYes.click();

}catch(org.openqa.selenium.NoSuchElementException ignore){
        //TODO: do nothing
}

Hope it helps.

网友答案:

You can also do this as:

WebDriverWait wait = new WebDriverWait(driver, 10); // Have a wait object with 10 sec(or whatever u prefer) to enforce on driver object stating for max time it should wait for the conditions
try{
    wait.until(ExpectedConditions.elementToBeClickable(By.id("idYes"))).click(); // will explicitly wait for the element to be clickable, else throw timeout exception
}catch(TimeoutException toe){
    System.out.println("Check box not present, hence skipping. " + toe); // here you can log or sysout the reason for skipping accompanied with exception
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: