2 回答

TA貢獻1818條經驗 獲得超8個贊
您可以使用findElements()來檢查該元素是否在網頁上。
findElements()- 如果沒有具有給定定位器的元素,則返回空列表-如果元素不在頁面上,則
findElement()拋出NoSuchElementException
試試下面的代碼:
List<WebElement> elements = driver.findElements(By.locator);
if(!elements.isEmpty()) {
if(elements.get(0).isDisplayed()) {
elements.get(0).click();
}
else {
// element not visible
}
}else{
// here mention code if element not present
}
建議:使用相對 xpath 而不是絕對 xpath。或嘗試使用 CSS 選擇器。

TA貢獻1772條經驗 獲得超5個贊
嘗試使用 try catch 而不是 if else。
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);
}
添加回答
舉報