Selenium java中isDisplayed()的替代方法

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();

    }

}

我希望如果显示元素然后执行任务 else 调用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)"



智慧大石
浏览 225回答 2
2回答

弑天下

您可以使用findElements()来检查该元素是否在网页上。findElements()- 如果没有具有给定定位器的元素,则返回空列表-如果元素不在页面上,则findElement()抛出NoSuchElementException试试下面的代码:List<WebElement> elements = driver.findElements(By.locator);if(!elements.isEmpty()) {&nbsp; &nbsp; if(elements.get(0).isDisplayed()) {&nbsp; &nbsp; &nbsp; &nbsp;elements.get(0).click();&nbsp; &nbsp; }&nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp;// element not visible&nbsp;&nbsp; &nbsp; }}else{&nbsp; // here mention code if element not present&nbsp; &nbsp;}建议:使用相对 xpath 而不是绝对 xpath。或尝试使用 CSS 选择器。

月关宝盒

尝试使用 try catch 而不是 if else。&nbsp;try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (webElements.newCohortElm.isDisplayed()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; doApply();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; catch (Exception e){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SeleniumUtils.click(getDriver(), webElements.createCohortSelectionFromMenu);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; webElements.cohortname.sendKeys("private_cohort_test");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; SeleniumUtils.click(getDriver(), webElements.createCohortButton);&nbsp; &nbsp; &nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java