Back to Resources

Blog

Posted June 1, 2023

Getting Started with XPath in Selenium

Selenium is the industry-standard, open-source testing automation framework. This blog explains how to use XPath as a web element locator in Selenium.

What is Selenium? 

Selenium is a popular open-source framework developed specifically for automated cross-browser testing of web applications. Selenium testing supports common scripting languages, including Node.js, Java, Python, Ruby, and C#, allowing developers, QA, and even project managers to develop and review tests for their apps, speeding up the time to market.

Selenium 4, the latest version of the Selenium test tool, natively allows developers and testers to write test scripts in different programming languages (Python, Java, Ruby, C#, NodeJS, etc.) that can run on different operating systems and browsers without modification.

For more information on Selenium 4, see the following resources:

What is XPath in Selenium? 

XPath is a query language that can be used to search for and locate elements in XML and HTML documents. XPath is the preferred locator when other CSS locators (ID, Class, etc.) that identify elements or unique attributes are not found in an XML/HTML document. XPath in Selenium follows an XML path to navigate through the HTML structure of a web page. 

Whenever a web page loads in a browser, it creates a Document Object Model (DOM) structure. An XPath expression, or command, is used to find any dynamic web element within the generated DOM

The growing number of browser types and versions makes automated testing a feasible alternative to manual testing. The ideal test tool for developers who want to move to automated testing is Selenium WebDriver, which is a free collection of open-source application programming interfaces (APIs) used to automate web application testing

The WebDriver code library provides methods to find dynamic web elements using a locator like XPath or others like ID, Class, or other CSS (Cascading Style Sheets) selectors. Although the XPath code is easy to obtain, it can be clumsy to write, brittle, and awkward to reverse engineer. This has led to the wider use of CSS selectors to identify objects in WebDriver. Despite having an initial learning curve, CSS selectors provide bindings that are easier to read, less brittle, and more closely integrated into the browser platform than XPath.  

XPath in Selenium syntax example

The following is an example of the general syntax of XPath in Selenium:

1
//Tagname[@AttibuteName = ‘value’]

XPath in Selenium Python

As one of the oldest programming languages, Python has a long-established global developer community that has released many packages for testing automation, including pytest, unittest, doctest, and others. With the growing number of browsers, automated cross-browser testing becomes necessary, particularly for any changes that require modification. Installing Selenium in Python’s high-level programming language environment, together with Selenium WebDriver and other automation tools, provides the functionality needed to run cross-browser tests. 

XPath in Selenium Python syntax example

The following is an example of the syntax for finding element in Selenium Python:

1
driver.find_element_by_xpath("//input[text()='Selenium']")

WebDriver for Python is a driver proxy for running Selenium testing automation in multiple frameworks, code editors, and IDEs. Python’s syntax in Selenium is both object-oriented and functional, allowing developers to use classes or functions. Selenium Python works with command-line tools, enabling developers to build continuous integration/continuous delivery (CI/CD) pipelines.

Finding Elements by XPath in Selenium

Before editing an HTML element in the DOM structure, the location of the specific web element first needs to be identified by its XML path. For this task, XPath is typically the easiest way to get started with locators in Selenium. XPath is also the preferred locator for inspecting elements on a page. If elements fail to be identified by general locators like ID, name, class name, etc., then XPath can be used to extract information from those web elements in an XML or HTML document. 

Other locators in Selenium can be used to search for elements using tags or CSS class names. Although ID and CSS selectors may be the fastest among the locators — it is possible to move from XPath to CSS — XPath in Selenium can handle more complex, dynamic searches. 

Finding an element in XPath syntax example

The following is an example of the syntax for finding an element in XPath:

1
//tag_name[@Attribute_name = “Value of attribute”]

Types of XPath in Selenium 

There are two ways to locate an element in XPath: Absolute XPath and Relative XPath. The paths are defined by their XPath node, either the point where the path initiates to the node where the element is located or a point somewhere along the DOM.

Absolute path

XPath can be used to locate an element in absolute terms. An absolute XPath expression contains the location of all elements from the root node (HTML), where the path starts, to the desired element. One challenge with this path type is that the whole XPath will fail to find the element if there is any change or adjustment of any node or tag along the defined XPath expression. 

Absolute XPath syntax example

The following is an example of absolute XPath syntax, which always begins with a single forward slash, “/.”

1
/html/body/div[1]/header/div/div[1]/div[3]/div/form/div[3]/div[1]/input

Relative path

XPath can also use terms relative to an element that does have an ID or name attribute. A relative XPath expression usually starts from the middle of the HTML DOM structure – there’s no need to start from the root node. Relative XPath expressions appear to be more reliable with less chance of a script breaking. 

Relative XPath syntax example

The following is an example of relative XPath syntax, which always begins with a double forward slash, “//.”

1
//*[@id=”twotabsearchtextbox”]

What are XPath Axes? 

XPath axes are used to find dynamic elements when a normal XPath element search method like ID, name, class name, etc., is not possible. The axes are defined from the current context node in an XML document to the node where the XPath is pointing. The path refers to the axis on which elements are lying relative to another given element. The identification of elements is determined by their relationship like parent, child, sibling, ancestor, and descendant to the context node. 

How to Write a Dynamic XPath in Selenium

To write a dynamic XPath in Selenium, log into the website where the test will be done and find the XPath extension in the Chrome browser (without any plugin). If the elements to be tested cannot be found by general locators like ID, name, tag name, class, or other attribute, use the XPath locator.

XPath in Selenium examples

1
1. Example syntax using a single attribute (relative XPath type):
2
3
// a [@href=’http://www.google.com’]
4
//input[@id=’name’]
5
//input[@name=’username’]
6
//img[@alt=’sometext’]
7
8
2. Example syntax using multiple attributes (relative XPath type):
9
10
//tagname[@attribute1=’value1’] [attribute2=’value2’]
11
//a[@id=’id1’] [@name=’namevalue1’]
12
//img[@src=’’] [@href=’’]
13
14
3. Example syntax of a search using “contains” (here, to create an account):
15
16
//tagname[contains(@attribute,’value1’)]
17
//input[contains(@id,’’)]
18
//input[contains(@name,’’)]
19
//a[contains(@href,’’)]
20
//img[contains(@src,’’)]
21
//div[contains(@id,’’)]
22
23
4. Example syntax of a search using “starts-with:”:
24
25
//tagname[starts-with(@attribute-name,’’)]
26
//id[starts-with(@id,’’)]
27
//a[starts-with(@href=’’)]
28
//img[starts-with(@src=’’)]
29
//div[starts-with(@id=’’)]
30
//input[starts-with(@id=’’)]
31
//button[starts-with(@id,’’)]
32
33
5. Example syntax for using the following node:
34
35
Xpath/following::again-ur-regular-path
36
//input[@id=’’]/following::input[1]
37
//a[@href=’’]/following::a[1]
38
//img[@src=’’]/following::img[1]
39
40
6. Example syntax for using the preceding node:
41
42
Xpath/preceding::again-ur-regular-path
43
//input[@id=’’]/ preceding::input[1]
44
//a[@href=’’]/ preceding::a[1]
45
//img[@src=’’]/ preceding::img[1]
46
47
7. Example syntax for using the absolute XPath type:
48
49
1-/html/head/body/div/input
50
51
8. Example syntax for text search in XPath:
52
53
Syntax- tagname[text()=’text which is visible on page’]
54
55
9. Example syntax for text search with ‘contains’:
56
57
/*[contains(text(),’Employee Distribution by Subunit’)]
58

Published:
Jun 1, 2023
Share this post
Copy Share Link

Ready to start testing with Selenium and Sauce Labs?

Let's go!

© 2023 Sauce Labs Inc., all rights reserved. SAUCE and SAUCE LABS are registered trademarks owned by Sauce Labs Inc. in the United States, EU, and may be registered in other jurisdictions.