Clicking on elements within an SVG using XPath (Selenium WebDriver).

We can click on elements with an SVG using XPath in Selenium. The SVG element has the tag name svg. It has attributes like width, height, viewBox, and so on.

To click the element with svg, we should identify the element then utilize the Actions class. We shall first move to that element with the moveToElement method and then apply the click method on it.

Finally, to actually perform the action, we have to use the build and execute methods. To identify the svg element with xpath, there is the local-name() function available.

Let us look at the html code of a svg element.


Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class SVGElement{
   public static void main(String[] args) {
      System.setProperty("", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element, enter text
      WebElement m= driver.findElement(By.xpath ("//*[local-name()='svg' and @data-icon='home']/*[localname()='path']"));
      // Action class to move and click element
      Actions a = new Actions(driver);