✅ 1. org.openqa.selenium.NoSuchElementException
Cause: Trying to locate an element that does not exist on the page.
Solutions:
-
Ensure the element is present in the DOM and visible.
-
Add waits:
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("elementId")));
-
Check locator correctness (
id
,xpath
,cssSelector
, etc.).
✅ 2. ElementNotInteractableException
Cause: Element is present but cannot be interacted with (e.g., it's hidden or disabled).
Solutions:
-
Use
WebDriverWait
to ensure it is clickable:WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("elementId")));
-
Scroll into view using JavaScript:
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
✅ 3. TimeoutException
Cause: Wait timed out before condition was met.
Solutions:
-
Increase wait time or optimize locator.
-
Use appropriate expected condition (e.g.,
presenceOfElementLocated
vsvisibilityOfElementLocated
).
✅ 4. StaleElementReferenceException
Cause: WebElement is no longer attached to the DOM.
Solutions:
-
Re-locate the element after page reload or DOM change:
element = driver.findElement(By.id("elementId"));
-
Use a try-catch block to retry locating the element.
✅ 5. SessionNotCreatedException
Cause: Browser version mismatch with WebDriver.
Solutions:
-
Make sure ChromeDriver/GeckoDriver matches your browser version.
-
Use WebDriverManager (for Maven):
WebDriverManager.chromedriver().setup();
✅ 6. WebDriverException: unknown error: DevToolsActivePort file doesn't exist
Cause: Usually in headless mode with Chrome on Linux.
Solutions:
-
Add Chrome options:
ChromeOptions options = new ChromeOptions(); options.addArguments("--no-sandbox"); options.addArguments("--disable-dev-shm-usage"); options.addArguments("--headless");
✅ 7. Deprecation Warnings
Cause: Some older APIs (like Thread.sleep
, implicitlyWait
without Duration
, etc.) are deprecated.
Solutions:
-
Replace deprecated code:
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
✅ 8. java.lang.NullPointerException
Cause: WebElement or WebDriver not initialized.
Solutions:
-
Check initialization:
WebDriver driver = new ChromeDriver(); // Not null
-
Ensure correct scope in frameworks like TestNG, JUnit, etc.
✅ 9. org.openqa.selenium.ElementClickInterceptedException
Cause: Another element overlays the clickable element (like a modal or popup).
Solutions:
-
Wait for overlay to disappear.
-
Use JS click:
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
✅ 10. IllegalStateException: The driver executable does not exist
Cause: Path to WebDriver not set correctly.
Solutions:
-
Set system property or use WebDriverManager:
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
✅ 11. WARNING: Invalid Status code=403 text=Forbidden java.io.IOException: Invalid Status code=403 text=Forbidden at org.asynchttpclient.netty.handler.WebSocketHandler.abort
Solution - Add the below code inside the initial setUp method (on base class)
Absolutely! Here’s a more comprehensive list of Selenium errors in Java, including causes, real-world scenarios, and solutions. Great for debugging and improving test reliability.
π COMMON SELENIUM JAVA ERRORS + FIXES
π΄ org.openqa.selenium.WebDriverException: chrome not reachable
Cause: The Chrome browser crashed or was closed unexpectedly during the session.
Fixes:
-
Ensure you’re not killing Chrome externally.
-
Add stability options:
options.addArguments("--no-sandbox", "--disable-dev-shm-usage");
π΄ org.openqa.selenium.TimeoutException
Cause: Explicit wait failed – element or condition didn't occur in time.
Fixes:
-
Use correct locator.
-
Add enough wait time.
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id")));
π΄ org.openqa.selenium.InvalidSelectorException
Cause: Syntax error in your selector (mostly with XPath).
Fixes:
-
Double-check the XPath:
By.xpath("//div[@class='className']") // ✅ By.xpath("div[@class='className']") // ❌
π΄ org.openqa.selenium.UnhandledAlertException
Cause: Alert/popup opened and not handled before next action.
Fixes:
Alert alert = driver.switchTo().alert();
alert.accept(); // or alert.dismiss();
π΄ org.openqa.selenium.ElementNotVisibleException
(older Selenium)
π‘ Now replaced with ElementNotInteractableException
.
Fixes:
-
Wait for visibility using:
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("id")));
π΄ org.openqa.selenium.JavascriptException
Cause: Error in JS execution using JavascriptExecutor
.
Fixes:
-
Check the JS syntax.
((JavascriptExecutor) driver).executeScript("window.scrollTo(0, document.body.scrollHeight);");
π΄ org.openqa.selenium.NoSuchFrameException
Cause: Trying to switch to a frame that doesn’t exist.
Fixes:
-
Check the frame name or index.
-
Wait until frame is available:
driver.switchTo().frame("frameName");
π΄ java.lang.IllegalArgumentException: Argument is not valid
Cause: Wrong argument in method (often with locators or waits).
Fixes:
-
Review your method call:
driver.findElement(By.xpath("")) // ❌ Empty string!
π΄ org.openqa.selenium.InvalidElementStateException
Cause: Trying to type into a read-only input or disabled field.
Fixes:
-
Check if the field is enabled:
if (element.isEnabled()) { element.sendKeys("Hello"); }
π΄ org.openqa.selenium.ElementClickInterceptedException
Cause: Something (like a banner or loader) is blocking the element.
Fixes:
-
Use JS click:
((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
π΄ org.openqa.selenium.InvalidSessionIdException
Cause: Trying to interact with a closed browser or driver.
Fixes:
-
Ensure
driver.quit()
or test teardown hasn't run prematurely. -
Avoid reusing closed sessions.
π΄ org.openqa.selenium.UnsupportedCommandException
Cause: Using a command not supported by the browser version or driver.
Fixes:
-
Upgrade your Selenium and browser driver versions.
-
Avoid deprecated commands.
π΄ org.openqa.selenium.SessionNotCreatedException
Cause: Browser-driver mismatch.
Fixes:
-
Use WebDriverManager:
WebDriverManager.chromedriver().setup();
π§° Bonus Tip: Use Try-Catch for Robustness
try {
WebElement el = driver.findElement(By.id("myId"));
el.click();
} catch (NoSuchElementException e) {
System.out.println("Element not found: " + e.getMessage());
}
Awesome! Since we're working with Selenium + Java, and possibly TestNG, JUnit, or Cucumber, here’s a quick breakdown of how to handle Selenium errors framework-wise, plus some tips to improve your automation setup.
π§ͺ If You’re Using TestNG
✅ Retry Failed Tests (Automatic Retry)
public class RetryAnalyzer implements IRetryAnalyzer {
private int retryCount = 0;
private static final int maxRetryCount = 2;
public boolean retry(ITestResult result) {
if (retryCount < maxRetryCount) {
retryCount++;
return true;
}
return false;
}
}
Then annotate your test:
@Test(retryAnalyzer = RetryAnalyzer.class)
public void testMethod() {
// test code
}
π§ͺ If You’re Using JUnit
✅ Expected Exception Handling
@Test(expected = NoSuchElementException.class)
public void testNoSuchElement() {
driver.findElement(By.id("notThere")).click();
}
✅ Try-Catch With Assert Fail
@Test
public void testSafeClick() {
try {
driver.findElement(By.id("button")).click();
} catch (NoSuchElementException e) {
Assert.fail("Button not found: " + e.getMessage());
}
}
π§ͺ If You’re Using Cucumber (BDD)
✅ Hooks for Error Handling and Screenshots
@After
public void tearDown(Scenario scenario) {
if (scenario.isFailed()) {
// take screenshot
final byte[] screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.BYTES);
scenario.attach(screenshot, "image/png", "screenshot");
}
driver.quit();
}
⚡ Bonus: Recommended Project Structure
src/test/java/
├── base/ # Driver setup, base classes
├── pages/ # Page Object Models
├── tests/ # Test classes (TestNG or JUnit)
├── stepDefinitions/ # For Cucumber
└── utils/ # Helpers (screenshot, waits, etc.)
π§ Pro Tips
-
Use WebDriverManager to avoid version mismatches.
-
Add custom exception handling in your framework base class.
-
Integrate Allure, ExtentReports, or Cucumber HTML for rich reporting.
-
For parallel execution, use TestNG’s
parallel="methods"
or JUnit 5 with@Execution(CONCURRENT)
.
No comments:
Post a Comment