What is Xpath[ Xpath stands for XML Path Language]:
XPath is used to locate elements on a webpage by navigating its HTML structure. In Selenium automation, when elements cannot be located using standard locators such as ID, and ClassName, XPath is used as an alternative method to identify elements on the webpage.
Syntax
//tagname[@attribute='value']
Example: //div[@id='header_block']
- //: Refers to the current node.
- Tagname: Specifies the tag name of the target node.
- @ Indicates an attribute selection.
- Attribute: Denotes the name of the attribute for the node.
- Value: Represents the value of the specified attribute.
Types Of Xpath:
1. Absolute XPath: shows the full path to an element starting from the very top of the webpage. It begins with a single slash ("/"), However, it's not very flexible because any small change in the page's structure can break the path.
Example: /html/body/div[5]/div[1]/div[2]/div/div/form/div/div/input
2. Relative XPath: starts from any point in the webpage, not the very top. It uses double slashes ("//") and is more reliable, so it doesn’t break with small changes on the page.
Example://form[@id='login_form']//input[@type='text']
Creating Basic XPath Expressions in Selenium WebDriver
XPath expressions select nodes or a list of nodes based on attributes such as ID, Name, and Class Name.
Below are Some more basic XPath expressions://div[@id='email_container']
//input[@type='text']
//input[@name='email']
//link[@href='https://softwaretestingbugblab.blogspot.com']
//*[@class='login_form_container']
text() – Find elements based on their text.
in this example, we tried to identify the element by using the text value of the attribute
//button[text()='login']
contains() – Finds elements that partially match a value.
In this example, we tried to identify the element by using the text/id value of the attribute
//input[contains(@id, 'login')]` or //input[contains(text(), 'login')]
starts-with() – Finds elements where a value starts with specific text.
Example: `//input[starts-with(@id, 'login')]`
last() – Select the last element in a group.
Example: `(//div)[last()]`
position() – Select an element based on its position or index.
Example: `//div[@id='loginform']//input[1]
not() – Excludes elements that match a certain condition.
Example: //input[not(@disabled)]
//input[not(@Enabled)]
How to use AND & OR operators in selenium Xpath:
Use AND to select an element that meets both conditions.
Syntax: //tagname[@Attribute1='Value1' and @Attribute2='Value2']
Example: Select an element with both attributes:
//button[@name='login' and @type='submit']
Use OR to select an element that meets either condition.
Syntax: //tagname[@Attribute1='Value1' or @Attribute2='Value2']
Example: Select an element with either "element 1" or "element 2":
//button[@name='login' or @id='login_link']
Comments
Post a Comment