How to use xPath in Selenium WebDriver to grab SVG elements?


We can use xpath to grab SVG elements with Selenium Webdriver. A SVG element is identified with tagname svg. The svg image has the attributes like width and height attributes.

Let us investigate the html code of a svg element.

To create a xpath for a svg element, we have the syntax as //*[local-name()='svg'].

The local-name function is mandatory for creating a xpath of a svg element. So for the xpath expression for the image highlighted in the above image should be −

//*[local-name()='svg' and @data-icon='home']/*[local-name()='path']

Here, data-icon is an attribute of the svg tag element which is added accompanied with @ symbol. The [local-name()='path'] is included since it is the child of the svg tagname.

Let us validate the xpath we have created, within the Console tab.

The image which is a SVG element before the Home menu gets highlighted with our XPath.

Example

Code Implementation.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
public class SVGElement{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      // wait of 5 seconds
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      driver.get("https://www.tutorialspoint.com/index.htm");
      // identify element
      WebElement m= driver.findElement(By.xpath("//*[local-name()='svg' and @dataicon='home']/*[local-name()='path']"));
      // Action class to move and click element
      Actions act = new Actions(driver);
      act.moveToElement(m).
      click().build().perform();
      driver.quit();
   }
}

Updated on: 15-Sep-2023

26K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements