003 7.xpath Methods

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 4

X-path and More

X-Path

 Syntax : //tagname[@attribute='value']

 // : Select current node.


 Tagname: Tagname of the particular node.
 @: Select attribute.
 Attribute: Attribute name of the node.
 Value: Value of the attribute.

 E.g. : //a[@id=‘login’]
Types of X-path
Absolute XPath
 It is the direct and lengthy way to find an element.
E.g. : /html/body/div[1]/div[3]/div/div[2]/main/div/div[1]/div/article/div/div/div[3]/div[1]/div/div/h2[2]/
div[1]/div/div[2]/input
 The problem with absolute XPath is that if we make any changes in the Webpage before the
position of that element then that XPath fails.
 It begins with the single forward slash(/) ,which means you can select the element from the root
node.

Relative XPath
 For Relative XPath, the path starts from the middle of the HTML DOM structure.
E.g. : .//input[@name='firstname']
 It starts with double forward slash (//), which means it can search the element anywhere at the
webpage.
 You can start from the middle of the HTML DOM structure with no need to write a long XPath.
Methods of X-path
 Contains() – As the name suggests it checks if an attribute contains the specific value or
not.
E.g. xpath = .//input[contains(@id,’user’)]
 OR & AND – This is very simple we all might’ve used this in any different programming
language, this is no different. To use multiple conditions at once we use OR & AND.
E.g. xpath = .//input[@id=‘username’ OR @name=‘username’]
 Starts-With Function – This function checks if the attribute of an element starts with that
particular value or not.
E.g. xpath = .//input[starts-with(@id,’user’)]
 Text() – This function checks if the text of the tag matches the mentioned value.
E.g. xpath = .//label[text()=‘Username’]
 Using Index – When your xpath return more then 1 element you can use index to specify
the one you’re searching for.
E.g. xpath = (.//a[text()=‘New Item’])[1]

You might also like