How to click on an image using Selenium in Java

Click on an image using Selenium in Java

Selenium is a portable software testing framework for web applications that supports multiple languages including Java, C#, Ruby, and Python.

In this shot, we discuss how to click an image using Selenium in Java.

To begin, let’s add the following dependency to pom.xml.

<dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.3.0</version>
</dependency>

The click() method

The click() method is used to click on any web element.

In order to click on an image, we need to follow the steps below:

  1. Get the selector for the image to be clicked.
  2. Locate the element using Selenium, depending on the selector chosen in step 1.
  3. Once the web element is retrieved, invoke the click() method on the element.

Code

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Main{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver","path to driver");
String url = "https://educative.io/";
WebDriver driver = new FirefoxDriver();
driver.get(url);
String cssSelectorForImage = "#__next > div.ed-grid > div.ed-grid-main > div > div.w-full.-mt-2.sm\\:mt-0 > div > div.w-full.lg\\:w-3\\/4.mt-12 > div > div > div > div:nth-child(1) > svg";
driver.findElement(By.cssSelector(cssSelectorForImage)).click();
driver.close();
}
}

Explanation

  • Lines 1–3: We import the relevant classes and packages.
  • Line 9: We define the url to retrieve.
  • Line 10: We define the Firefox driver.
  • Line 11: We retrieve the HTML page of the url using the get() method.
  • Line 12: We define the CSS selector for the image.
  • Line 13: We obtain the element with the selector using the findElement() method. We then invoke the click() method on the element object.
  • Line 14: We close the driver.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved