public boolean isElementPresent(By locator) {
try {
driver.findElement(locator);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
Преимущества:
Недостатки:
public boolean isElementPresent(By locator, long timeoutSeconds) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeoutSeconds));
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
return true;
} catch (TimeoutException e) {
return false;
}
}
Преимущества:
Недостатки:
public boolean isElementPresent(By locator) {
return !driver.findElements(locator).isEmpty();
}
Особенности:
public boolean isElementPresent(By locator, boolean checkVisibility, long timeout) {
try {
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(timeout));
if (checkVisibility) {
wait.until(ExpectedConditions.visibilityOfElementLocated(locator));
} else {
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
}
return true;
} catch (TimeoutException e) {
return false;
}
}
Выбор подходящего условия:
presenceOfElementLocated
- элемент в DOMvisibilityOfElementLocated
- элемент видимыйelementToBeClickable
- элемент кликабельныйОптимальный таймаут:
// Хорошая практика - выносить в конфигурацию
long defaultTimeout = Long.parseLong(Config.getProperty("element.timeout.seconds"));
Логирование:
public boolean isElementPresent(By locator) {
try {
driver.findElement(locator);
log.debug("Element found: " + locator);
return true;
} catch (NoSuchElementException e) {
log.debug("Element not found: " + locator);
return false;
}
}
public boolean isElementPresentJS(By locator) {
JavascriptExecutor js = (JavascriptExecutor)driver;
return (Boolean)js.executeScript(
"return document.querySelector(arguments[0]) !== null",
locator.toString().replace("By.cssSelector: ", ""));
}
public boolean isElementPresentInFrames(By locator) {
try {
driver.findElement(locator);
return true;
} catch (NoSuchElementException e) {
// Поиск во всех iframe
for (WebElement frame : driver.findElements(By.tagName("iframe"))) {
driver.switchTo().frame(frame);
boolean present = isElementPresent(locator);
driver.switchTo().defaultContent();
if (present) return true;
}
return false;
}
}
Смешение presence и visibility:
Игнорирование StaleElementReferenceException:
// Нужно учитывать
catch (StaleElementReferenceException e) {
return false;
}
Использование Thread.sleep():
findElements().isEmpty()
для простых случаевWebDriverWait
и ExpectedConditions
Профессиональный совет: Создайте класс ElementUtils
с набором статических методов для разных сценариев проверки элементов (isPresent, isVisible, isClickable и т.д.) для удобного повторного использования в проекте.