SlideShare a Scribd company logo
1 of 13
Download to read offline
Using XPath in
Selenium: All you
need to know
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
Introduction
Navigating the complex web world as an automation tester aims to ensure the delivery of an
application that is bug-free and seamless and offers exceptional user experiences. One common
challenge on this journey is locating web elements accurately and efficiently to interact with them.
Selenium WebDriver helps identify web elements efficiently with various tools and locators. Today,
several enterprises are leveraging XPath owing to its greater flexibility and compatibility with old
browsers, making it one of its most powerful and versatile locators.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
What is XPath in Selenium?
XPath, or XML Path Language, is a language for navigating an XML document and
selecting nodes. In the context of Selenium WebDriver, XPath is used as a locator to
find web elements on a page. It is a powerful tool that can navigate the webpage's
HTML structure, making it extremely useful when other simple locators like ID or
class fail to find the elements reliably.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
There are primarily two types of
XPath used in Selenium:
• Absolute XPath
• Relative XPath
Types of XPath in
Selenium
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
It's a direct path from the root element to the desired element. It starts from the root
node and ends with the desired node, providing a complete path. However, it's brittle
and can break with small changes in the web page's structure.
Here's a Selenium XPath example for how you might use an absolute XPath in your
Selenium code. Suppose you have the following HTML structure:
<html>
<body>
<div>
<p>Hello, world!</p>
</div>
</body>
</html>
Absolute XPath(1/2)
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
To find the <p> tag using an absolute XPath, you would start at the root <html> tag and
provide the full path to the <p> tag:
In this case, the XPath "/html/body/div/p" represents the absolute path from the root
<html> tag to the desired <p> tag.
In several scenarios, however, absolute XPath is not recommended unless necessary
because it's brittle, and any change in the HTML structure may cause your test to fail.
WebElement paragraph = driver.findElement(By.xpath("/html/body/div/p"));
Absolute XPath(2/2)
Relative XPath(1/2)
It starts from any node and ends with the node you
want to select. It's more flexible and preferred in
most cases, as it's not affected by changes in other
parts of the HTML structure. A relative XPath allows
you to locate elements starting from any location
within the HTML document, not just the root. The
relative XPath expression usually starts with //.
Here's an example of using relative XPath in
Selenium with Python:
```python
from selenium import webdriver
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# Navigate to a website
driver.get("https://example.com")
# Find an element using relative XPath
element = driver.find_element_by_xpath("//div[@id='myDiv']/p[2]")
# Perform actions on the element
element.click()
# Close the browser
driver.quit(
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
In the example mentioned in the previous slide , we first import the necessary modules from the Selenium library. Then,
we create a new instance of the Firefox driver and navigate to a website (in this case, "https://example.com").
Next, we find an element using a relative XPath expression. The XPath used in this example selects the second `<p>`
element inside a `<div>` element with the id "myDiv". You can modify the XPath expression to suit your specific needs.
After finding the element, you can perform various actions on it, such as clicking it, entering text, or retrieving its
attributes.
Finally, we close the browser using the `quit()` method to clean up and release the resources used by the driver.
Using relative XPaths is generally recommended over absolute XPaths because they are more resilient to page
structure changes.
Relative XPath(2/2)
Types of XPath locators
This locator allows you to identify an element by its id
attribute.
XPath locator by ID
This locator can identify elements based on their
class attribute.
XPath locator by class name
XPath locator by tag name
This locator can identify elements by their HTML
tag name.
This locator identifies elements by their name
attribute.
XPath locator by name
XPath locator by text
This locator identifies elements based on their
inner text.
XPath locator using contains
This locator can identify elements based on a
substring of one of their attribute values.
XPath locator using starts-with
This locator identifies elements whose attribute
values start with a particular string.
Path locator using ends-with
This locator can identify elements whose
attribute values end with a particular string.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
What is chained XPath in
Selenium?
Chained XPath in Selenium is a concept where multiple XPaths are used in conjunction to
locate an element that might not be uniquely identifiable by a single XPath expression. In other
words, instead of writing one absolute XPath, we can separate it into multiple relative XPaths.
This approach can be specifically useful when dealing with complex or dynamic web structures
where elements are not easily accessible through single, unique identifiers. Chaining XPaths
can provide more precision and robustness in element location strategy, thus making the
automation scripts more stable.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
What are XPath Axes?
Following Ancestor Child Parent
XPath Axes are used for finding dynamic elements when normal XPath element search methods like
name, ID, class name, etc., aren't possible. XPath Axes navigate through elements in the XML
structure of a webpage. They allow you to locate elements based on their relationship with other
elements, like parent, sibling, child, ancestor, or descendant. Here are few XPath methods:
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
How HeadSpin helps
streamline Selenium
utilization
HeadSpin offers a robust AI-driven testing Platform
with easy integration with multiple automation
frameworks to improve testing efficiency and ship
faster to the market.
1
Support for Selenium Webdriver
2
Parallel Testing
3
Integration with CI/CD pipelines
4
Integration with CI/CD pipelines
4
Integration with CI/CD pipelines
4
Integration with CI/CD pipelines
Conclusion
XPath is critical in Selenium testing, offering a robust method for locating elements within
the web page's DOM. Understanding and utilizing XPath's capabilities can greatly improve
the effectiveness and efficiency of your Selenium tests. Moreover, with platforms like
HeadSpin, you can enhance your testing capabilities further, leveraging its unique features
aligned with Selenium standards.
Reference Link: https://www.headspin.io/blog/using-xpath-in-selenium-effectively
Copyright © 2023 HeadSpin, Inc. All Rights Reserved.

More Related Content

Similar to Using XPath in Selenium_ All you need to know.pdf

Automated_Testing_Selenium
Automated_Testing_SeleniumAutomated_Testing_Selenium
Automated_Testing_SeleniumJagdish Kaushal
 
Semantics In Declarative Systems
Semantics In Declarative SystemsSemantics In Declarative Systems
Semantics In Declarative SystemsOptum
 
Automatedtestingwithselenium shubham jain
Automatedtestingwithselenium shubham jainAutomatedtestingwithselenium shubham jain
Automatedtestingwithselenium shubham jainPrashant Gurav
 
QER : query entity recognition
QER : query entity recognitionQER : query entity recognition
QER : query entity recognitionDhwaj Raj
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullySpringPeople
 
Session on Selenium Powertools by Unmesh Gundecha
Session on Selenium Powertools by Unmesh GundechaSession on Selenium Powertools by Unmesh Gundecha
Session on Selenium Powertools by Unmesh GundechaAgile Testing Alliance
 
New Features of Chropath for XPath and CSS Selectors | Edureka
New Features of Chropath for XPath and CSS Selectors | EdurekaNew Features of Chropath for XPath and CSS Selectors | Edureka
New Features of Chropath for XPath and CSS Selectors | EdurekaEdureka!
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningSyed Irtaza Ali
 
Advanced full text searching techniques using Lucene
Advanced full text searching techniques using LuceneAdvanced full text searching techniques using Lucene
Advanced full text searching techniques using LuceneAsad Abbas
 
Elasticsearch quick Intro (English)
Elasticsearch quick Intro (English)Elasticsearch quick Intro (English)
Elasticsearch quick Intro (English)Federico Panini
 
Object identification and its management
Object identification and its managementObject identification and its management
Object identification and its managementVinay Kumar Pulabaigari
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalystdwm042
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web DevelopmentRobert J. Stein
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migrationAmit Sharma
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화NAVER D2
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화Henry Jeong
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09Pyxis Technologies
 
Advanced SEO for Web Developers
Advanced SEO for Web DevelopersAdvanced SEO for Web Developers
Advanced SEO for Web DevelopersNathan Buggia
 

Similar to Using XPath in Selenium_ All you need to know.pdf (20)

Automated_Testing_Selenium
Automated_Testing_SeleniumAutomated_Testing_Selenium
Automated_Testing_Selenium
 
Semantics In Declarative Systems
Semantics In Declarative SystemsSemantics In Declarative Systems
Semantics In Declarative Systems
 
Automatedtestingwithselenium shubham jain
Automatedtestingwithselenium shubham jainAutomatedtestingwithselenium shubham jain
Automatedtestingwithselenium shubham jain
 
QER : query entity recognition
QER : query entity recognitionQER : query entity recognition
QER : query entity recognition
 
Mastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium SuccessfullyMastering Test Automation: How To Use Selenium Successfully
Mastering Test Automation: How To Use Selenium Successfully
 
Session on Selenium Powertools by Unmesh Gundecha
Session on Selenium Powertools by Unmesh GundechaSession on Selenium Powertools by Unmesh Gundecha
Session on Selenium Powertools by Unmesh Gundecha
 
New Features of Chropath for XPath and CSS Selectors | Edureka
New Features of Chropath for XPath and CSS Selectors | EdurekaNew Features of Chropath for XPath and CSS Selectors | Edureka
New Features of Chropath for XPath and CSS Selectors | Edureka
 
My 70-480 HTML5 certification learning
My 70-480 HTML5 certification learningMy 70-480 HTML5 certification learning
My 70-480 HTML5 certification learning
 
Advanced full text searching techniques using Lucene
Advanced full text searching techniques using LuceneAdvanced full text searching techniques using Lucene
Advanced full text searching techniques using Lucene
 
Elasticsearch quick Intro (English)
Elasticsearch quick Intro (English)Elasticsearch quick Intro (English)
Elasticsearch quick Intro (English)
 
Object identification and its management
Object identification and its managementObject identification and its management
Object identification and its management
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Struts2
Struts2Struts2
Struts2
 
User and group security migration
User and group security migrationUser and group security migration
User and group security migration
 
[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화[2D1]Elasticsearch 성능 최적화
[2D1]Elasticsearch 성능 최적화
 
[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화[2 d1] elasticsearch 성능 최적화
[2 d1] elasticsearch 성능 최적화
 
Struts 2
Struts 2Struts 2
Struts 2
 
FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09FluentSelenium Presentation Code Camp09
FluentSelenium Presentation Code Camp09
 
Advanced SEO for Web Developers
Advanced SEO for Web DevelopersAdvanced SEO for Web Developers
Advanced SEO for Web Developers
 

Recently uploaded

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

Using XPath in Selenium_ All you need to know.pdf

  • 1. Using XPath in Selenium: All you need to know Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 2. Introduction Navigating the complex web world as an automation tester aims to ensure the delivery of an application that is bug-free and seamless and offers exceptional user experiences. One common challenge on this journey is locating web elements accurately and efficiently to interact with them. Selenium WebDriver helps identify web elements efficiently with various tools and locators. Today, several enterprises are leveraging XPath owing to its greater flexibility and compatibility with old browsers, making it one of its most powerful and versatile locators. Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 3. What is XPath in Selenium? XPath, or XML Path Language, is a language for navigating an XML document and selecting nodes. In the context of Selenium WebDriver, XPath is used as a locator to find web elements on a page. It is a powerful tool that can navigate the webpage's HTML structure, making it extremely useful when other simple locators like ID or class fail to find the elements reliably. Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 4. There are primarily two types of XPath used in Selenium: • Absolute XPath • Relative XPath Types of XPath in Selenium Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 5. It's a direct path from the root element to the desired element. It starts from the root node and ends with the desired node, providing a complete path. However, it's brittle and can break with small changes in the web page's structure. Here's a Selenium XPath example for how you might use an absolute XPath in your Selenium code. Suppose you have the following HTML structure: <html> <body> <div> <p>Hello, world!</p> </div> </body> </html> Absolute XPath(1/2) Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 6. Copyright © 2023 HeadSpin, Inc. All Rights Reserved. To find the <p> tag using an absolute XPath, you would start at the root <html> tag and provide the full path to the <p> tag: In this case, the XPath "/html/body/div/p" represents the absolute path from the root <html> tag to the desired <p> tag. In several scenarios, however, absolute XPath is not recommended unless necessary because it's brittle, and any change in the HTML structure may cause your test to fail. WebElement paragraph = driver.findElement(By.xpath("/html/body/div/p")); Absolute XPath(2/2)
  • 7. Relative XPath(1/2) It starts from any node and ends with the node you want to select. It's more flexible and preferred in most cases, as it's not affected by changes in other parts of the HTML structure. A relative XPath allows you to locate elements starting from any location within the HTML document, not just the root. The relative XPath expression usually starts with //. Here's an example of using relative XPath in Selenium with Python: ```python from selenium import webdriver # Create a new instance of the Firefox driver driver = webdriver.Firefox() # Navigate to a website driver.get("https://example.com") # Find an element using relative XPath element = driver.find_element_by_xpath("//div[@id='myDiv']/p[2]") # Perform actions on the element element.click() # Close the browser driver.quit( Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 8. Copyright © 2023 HeadSpin, Inc. All Rights Reserved. In the example mentioned in the previous slide , we first import the necessary modules from the Selenium library. Then, we create a new instance of the Firefox driver and navigate to a website (in this case, "https://example.com"). Next, we find an element using a relative XPath expression. The XPath used in this example selects the second `<p>` element inside a `<div>` element with the id "myDiv". You can modify the XPath expression to suit your specific needs. After finding the element, you can perform various actions on it, such as clicking it, entering text, or retrieving its attributes. Finally, we close the browser using the `quit()` method to clean up and release the resources used by the driver. Using relative XPaths is generally recommended over absolute XPaths because they are more resilient to page structure changes. Relative XPath(2/2)
  • 9. Types of XPath locators This locator allows you to identify an element by its id attribute. XPath locator by ID This locator can identify elements based on their class attribute. XPath locator by class name XPath locator by tag name This locator can identify elements by their HTML tag name. This locator identifies elements by their name attribute. XPath locator by name XPath locator by text This locator identifies elements based on their inner text. XPath locator using contains This locator can identify elements based on a substring of one of their attribute values. XPath locator using starts-with This locator identifies elements whose attribute values start with a particular string. Path locator using ends-with This locator can identify elements whose attribute values end with a particular string. Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 10. What is chained XPath in Selenium? Chained XPath in Selenium is a concept where multiple XPaths are used in conjunction to locate an element that might not be uniquely identifiable by a single XPath expression. In other words, instead of writing one absolute XPath, we can separate it into multiple relative XPaths. This approach can be specifically useful when dealing with complex or dynamic web structures where elements are not easily accessible through single, unique identifiers. Chaining XPaths can provide more precision and robustness in element location strategy, thus making the automation scripts more stable. Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 11. What are XPath Axes? Following Ancestor Child Parent XPath Axes are used for finding dynamic elements when normal XPath element search methods like name, ID, class name, etc., aren't possible. XPath Axes navigate through elements in the XML structure of a webpage. They allow you to locate elements based on their relationship with other elements, like parent, sibling, child, ancestor, or descendant. Here are few XPath methods: Copyright © 2023 HeadSpin, Inc. All Rights Reserved.
  • 12. Copyright © 2023 HeadSpin, Inc. All Rights Reserved. How HeadSpin helps streamline Selenium utilization HeadSpin offers a robust AI-driven testing Platform with easy integration with multiple automation frameworks to improve testing efficiency and ship faster to the market. 1 Support for Selenium Webdriver 2 Parallel Testing 3 Integration with CI/CD pipelines 4 Integration with CI/CD pipelines 4 Integration with CI/CD pipelines 4 Integration with CI/CD pipelines
  • 13. Conclusion XPath is critical in Selenium testing, offering a robust method for locating elements within the web page's DOM. Understanding and utilizing XPath's capabilities can greatly improve the effectiveness and efficiency of your Selenium tests. Moreover, with platforms like HeadSpin, you can enhance your testing capabilities further, leveraging its unique features aligned with Selenium standards. Reference Link: https://www.headspin.io/blog/using-xpath-in-selenium-effectively Copyright © 2023 HeadSpin, Inc. All Rights Reserved.