Q3. How is XPath used in Selenium? What is the difference between Absolute and Relative XPath?
Answer:
XPath (XML Path Language) is used in Selenium to navigate through elements and attributes in an HTML document. XPath is useful when elements do not have fixed IDs or names.
Types of XPath:
- Absolute XPath: Starts from root node /html/…
- Relative XPath: Starts from current context node using //
Aspect | Absolute XPath | Relative XPath |
Syntax | /html/body/div[1]/form/input[1] | //input[@id=’username’] |
Stability | Breaks easily if DOM changes | More stable and flexible |
Performance | Slightly faster | Easier to maintain |
Common XPath Functions:
- //tag[@attribute=’value’]
- contains(text(), ‘Login’)
- starts-with(@id, ‘user’)
Q4. Explain dynamic element handling using XPath Axes.
Answer:
Dynamic elements in web pages often have changing attributes like ID, Name, or Class. XPath Axes help navigate through such elements relative to other known elements.
Common XPath Axes:
- following – All nodes after the current one
👉 //*[@type=’text’]//following::input[1] (e.g., Password field) - preceding – All nodes before the current one
👉 //*[@type=’submit’]//preceding::input[1] - ancestor – Gets all ancestors (like div, form)
👉 //*[text()=’Enterprise Testing’]//ancestor::div - child – Direct children of a node
👉 //*[@id=’java_technologies’]/child::li - self – Refers to the current node
👉 //*[@type=’password’]//self::input
These are very helpful in complex or dynamically changing DOM structures.
👉The Next Questions-3: SELENIUM