有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我想通过SeleniumWebDriver在web应用程序中选择RadioType复选框,只要它可用

只要可用,我想通过selenium web驱动程序在我的web应用程序中选中radio type复选框 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>

它使用以下web驱动程序代码:

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

我还尝试了:(在本例中,选中了单选按钮,但在其他情况下不忽略)

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

idYes.click();}

或另一次尝试:(在这种情况下,单选按钮未选中)

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

idYes.clickIfElement Present();}

但当上述元素在不同的场景中不可用时,它就失败了
预期行为是:如果元素存在,请选择或忽略


共 (2) 个答案

  1. # 1 楼答案

    将代码放入try-catch块。在catch块中,忽略发生的任何错误

    例如

    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
    }
    

    希望能有帮助

  2. # 2 楼答案

    您还可以通过以下方式执行此操作:

    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
    }