How to handle SVG elements in Selenium Java

Introduction

The SVG element will not support our standard format of XPath like “//div[@class=’userName’]”. Writing the XPath for the SVG elements is always troublesome. So in this blog, we can understand the easy and simple way to write the XPath for the SVG elements. Before that let’s have a look at what SVG elements are.

SVG (Scalable Vector Graphics) is a web-friendly vector file format for displaying the application's two-dimensional graphics, charts & illustrations. It has several methods for drawing paths, circles, boxes, and graphic and text images. One of the main advantages of SVG is that it is a text-based format which improves the accessibility of the website.


Solution

Let’s get more understanding with some examples of SVG elements. From the below image, the marked icons are some examples of SVG elements.

image_2023_05_09T13_22_47_171Z

The below figure shows the DOM for the Chat icon displayed in the right corner, The Chat icon is developed using SVG and this is how it is shown in DOM. It is developed using the ‘svg’ as the parent tag, and ‘g’ & ‘path’ as subtags.

image_2023_05_09T13_22_52_569Z

So if we try to follow our usual method, the element won’t be identified as shown below figure.

image_2023_05_09T13_22_57_788Z

Identifying SVG elements from DOM to use in our Xpath should be treated differently, and we do have a set of methods to cover.

name(), and local-name() are the methods that should be used while creating Xpath for the SVG elements. And there are some steps for that which are to be followed.

  • We have to use ‘*’ along with the double slash, i.e. //*
  • name() method should be used for locating the ‘svg’ tag, i.e. //*[name()='svg']
  • local-name() should be used for locating the subtags like ‘g’ or ‘path’ 
  • We can use ‘and’ & ‘@’ for grouping the attributes.

Example: //*[name()='svg']//*[local-name()='g' and @fill-rule='evenodd']

image_2023_05_09T13_23_02_063Z


Conclusion

Fetching the Xpath correctly plays a crucial role in Automation. There is a very high chance of getting a false positive if we fetch the incorrect Xpath. By implementing this logic, we are able to locate the Xpath for the SVG web elements. As automation testers, we should be aware of all the possible combinations to get the right Xpath.

Happy Learning!! 

Saibalu R