</>

Technology

Selenium

Difficulty

Beginner

Interview Question

How can we click on an element using Selenium WebDriver?

Use the click() method on a located WebElement to perform a mouse click action in Selenium.

Answer

Use the click() method on a WebElement to simulate a mouse click.

Basic click:

Java
driver.findElement(By.id("loginBtn")).click();
driver.findElement(By.cssSelector(".btn-submit")).click();
driver.findElement(By.xpath("//button[text()=''Login'']")).click();

Best practice — wait before clicking:

Java
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
WebElement btn = wait.until(ExpectedConditions.elementToBeClickable(By.id("loginBtn")));
btn.click();

Click with JavaScript (for hidden or overlapping elements):

Java
WebElement btn = driver.findElement(By.id("loginBtn"));
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("arguments[0].click();", btn);

Common click errors:

ErrorCauseFix
ElementNotInteractableExceptionElement is hiddenJS click or scroll into view
ElementClickInterceptedExceptionAnother element overlapsWait for overlay to disappear
StaleElementReferenceExceptionDOM changed after findRe-find the element
TimeoutExceptionElement not found in timeIncrease wait timeout

Follow AutomateQA

Related Topics