B2B series: Create shorter XPath

Ferawati Hartanti Pratiwi
3 min readNov 8, 2021

--

https://doodleunlimited.com/wp-content/uploads/2016/10/0172_go-back-to-basics-to-advance-648x648.jpeg

Back To Basics chapter 1.

/html[1]/body[1]/div[1]/div[3]/form[1]/div[1]/div[1]/div[1]/div[1]/div[2]/input[1]— is the past that I want to forget. Did you do Inspect — go to Inspector tab — right click — click Copy menu — choose XPath ? I hope you read this article with a good attention. Let’s learn how to create a short XPath.

XPath

XPath is XML Path Language which uses path like syntax. The syntax is used to identify and navigate nodes in an XML document.

Syntax

Let’s open https://www.google.com/ for an example.

ancestor

Selects all ancestors (parent, grandparent, etc.) of the current node

Example :

  • //input/ancestor::div[contains(@class, ‘FPdoLc’)]
  • //a[text()=’Indonesia’]/ancestor::div[@class=’vcVZ7d’]

child

Selects all children of the current node

Example :

  • //*[@id=’SIvCob’]/child::a[1]
  • //*[contains(@class, ‘FPdoLc’)]/center/child::input[2]

descendant

Selects all descendants (children, grandchildren, etc.) of the current node

Example :

  • //*[@id=’SIvCob’]/descendant::a[text()=’Basa Bali’]

following

Selects everything in the document after the closing tag of the current node

Example :

  • //*[contains(@class, ‘FPdoLc’)]/following::div[1]

following-sibling

Selects all siblings after the current node

Example :

  • //*[@class=’gNO89b’]/following-sibling::input

parent

Selects the parent of the current node

Example :

  • //*[@class=’gNO89b’]/parent::center

preceding-sibling

Selects all siblings before the current node

Example :

  • //*[@class=’RNmpXc’]/preceding-sibling::input

We also could use plugin to create a short XPath.

--

--

Ferawati Hartanti Pratiwi
Ferawati Hartanti Pratiwi

Written by Ferawati Hartanti Pratiwi

Continuously striving to elevate QA standards with a quality-focused mindset

No responses yet