How to create dynamic XPath for SVG elements in Selenium?

We have discussed a lot more about mobile testing and its emulation with the Chrome browser. Also, we talked about various ways to locate web elements to make the test automation tasks easier for you. On further reading, you will find links to some of the awesome articles published here in the past on finding locators in a different way. Well, today we are going to talk about creating dynamic XPath for SVG elements in Selenium.

It becomes challenging to handle SVG web elements; a normal way of creating dynamic XPath is not going to work for you for SVG, hence, you need to pay extra attention to it. Let’s first understand the SVG concept of developing the web page, and then further I will tell you the ways to write dynamic XPath for SVG web objects.

Suggested Readings

What is SVG model?

SVG (Scalable Vector Graphics) is a web development technology that uses vector-based graphics in XML format. It follows W3C recommendations and every SVG element can be automated.

Advantages of SVG

Some of the advantages of SVG are listed below:

  • SVG objects are created, edited and debugged in any text editor
  • It is scalable and zoomable
  • SVG objects maintain the quality and attribute when they are zoomed in and out
  • They are formatted in open standard with pure XML convention
  • SVG objects are searched, scripted, indexed and further compressed

SVG’s DOM Structure

  • Every SVG image starts with <svg> tag
  • <circle> tag is used to draw a circle
  • X & Y coordinates are set with cx & cy attributes
  • The radius of the circle is defined with r attribute
  • Color inside the circle is defined with fill attribute
  • The SVG image is closed with </svg> tag

What are the challenges with SVGs XPath in Selenium?

You may face some challenges while writing XPath for SVG’s based web objects. Some of them are listed below:

  • Original axis methods of the XPath like following, siblings, preceding, etc doesn’t work with SVG objects
  • They are time-consuming
  • Sometimes they are not accurate
  • They might not be stable

SVG elements sample

Rules to write XPath for SVG elements in Selenium

Follow the below rule to write XPath for SVG elements. This will help you to identify SVG web objects.

Rule: Every SVG’s XPath will begin with [name()=’svg’] or [local-name()=’svg’] for their tags

Refer above image, suppose we want to identify path of the elements mentioned in third line, so the XPath would be like-

//*[name()=’svg’]//*[local-name()=’path’ and @id=’lineBC’]

Note: local-name() and name() can be used interchangeably.

Here, with SVG elements, traditional XPath will not work, hence, we should always follow the above pattern to identify SVG elements.

This was the complete tutorial to identify SVG elements in Selenium. Post your queries in comment below and do not forget to follow us on social media.

Join Inviul fb group

One Response

Leave a Reply