Selenium Java中isDisplayed()的替代方法

时间:2018-11-13 12:49:03

标签: java selenium

public void privateCohortCreation() {
    if(webElements.newCohortElm.isDisplayed()) {
        SeleniumUtils.click(getDriver(),webElements.createCohortSelectionFromMenu);
        webElements.cohortname.sendKeys("private_cohort_test");
        SeleniumUtils.click(getDriver(),webElements.createCohortButton);
    }
    else {
        doApply();
    }
}

我希望如果显示元素,则执行任务,否则调用doApply()方法。但这是一个例外

"no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/app-root/div/app-container/app-indv301/app-global-filters/div/ul/li[3]/app-cohort/div/div/app-status/div"} (Session info: chrome=70.0.3538.77)"

2 个答案:

答案 0 :(得分:2)

您可以使用MultiValueMap payload = new LinkedMultiValueMap(); // some json part named "request" HttpHeaders requestPartHeaders = new HttpHeaders(); requestPartHeaders.setContentType(MediaType.APPLICATION_JSON); HttpEntity<ConversionRequest> requestEntity = new HttpEntity<>(requestBean, requestPartHeaders); // InputStreamResource part named "file" HttpHeaders fileRequestHeaders = new HttpHeaders(); fileRequestHeaders.setContentDisposition(ContentDisposition.builder("form-data") .name("file") // name of the part in the map .filename("my-file-name.pdf") // <-- mandatory file name .build()); fileRequestHeaders.setContentType(MediaType.parseMediaType(fileMimeType)); HttpEntity<InputStreamResource> fileEntity = new HttpEntity<>(new InputStreamResource(fileOriginalStream), fileRequestHeaders); payload.add("request", requestEntity); payload.add("file", fileEntity); 来检查元素是否在网页上。

findElements()-如果没有给定定位符的元素,则返回空列表
findElements()-如果元素不在页面上,则抛出findElement()

尝试以下代码:

NoSuchElementException

建议::使用相对xpath而不是绝对xpath。或尝试使用CSS选择器。

答案 1 :(得分:0)

尝试使用try catch而不是其他方式

 try {
            if (webElements.newCohortElm.isDisplayed()) {
                doApply();
            }
        }
        catch (Exception e){
            SeleniumUtils.click(getDriver(), webElements.createCohortSelectionFromMenu);
            webElements.cohortname.sendKeys("private_cohort_test");
            SeleniumUtils.click(getDriver(), webElements.createCohortButton);
        }