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

SeleniumAutomation TestingTesting Tools

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.

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;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
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();
      driver.get("https://www.tutorialspoint.com/index.htm");
      // 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);
      a.moveToElement(m).
      click().build().perform();
   }
}

Output

raja
Published on 28-Dec-2020 15:35:12
Advertisements