![]()
Playwright Guide: How To Find Elements by XPath
The ability to locate elements on a web page is essential when using web automation libraries. While CSS selectors are often the go-to method for targeting elements, there are situations where they may fall short. This is where XPath shines, it offers a different way of navigating the complex structure of a web page.
In this guide, we will explore how to find elements by XPath in Playwright. We will go through step-by-step instructions and practical examples to help you master this valuable skill.
- TLDR: How To Find Elements by XPath
- What is XPath
- Understanding XPath Syntax
- Choosing Between XPath and CSS: What You Need to Know
- How to Find Elements with XPath
- Selecting Elements with XPath (page.locator() method)
- Waiting for XPath to be Available
- Performing Actions with XPath
- Real-world Applications: XPath in Practice
- XPath Best Practices: Maximizing Efficiency
- Conclusion
- More Web Scraping Guides
Need help scraping the web?
Then check out ScrapeOps, the complete toolkit for web scraping.
TLDR: How To Find Elements by XPath
When using Playwright, scripts adhering to a uniform design pattern for selecting elements through XPath typically involve the page.locator() method. The method returns an element locator that can be used to perform actions on this page/frame.
Below is a Playwright XPath query for finding an element on scrapethissite.com in our console.
Let's look at the following script:
const playwright = require("playwright");
async function getInnerText(params) {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
// We insert the desired URL of the page
await page.goto("https://www.scrapethissite.com/pages/simple/");
/**
We will insert the XPath expression that we got from our browser
inside the locator method.
**/
// The XPath expression selects the first country on the website
const element = await page.locator(
`//*[@id="countries"]/div/div[4]/div[1]/h3`
);
/**
Now that we have located the element we want, we can use the inner.text method to get the text inside.
**/
const innerText = await element.innerText();
console.log(innerText);
await browser.close();
}
getInnerText();
Andorra
In this script:
- We launched a Chromium browser instance using Playwright.
- A new browsing context and page were created within this browser instance.
- The
page.goto()method was used to navigate to the desired URL. - Inside the
<code>page.locator()</code>method, we inserted the XPath expression retrieved from the browser. This XPath expression selects the first country on the website. - After locating the desired element, its inner text was extracted using the
<code>innerText()</code>method. - The extracted inner text was then logged on the console.
- Finally, the browser instance was closed.
What is XPath
XPath (XML Path Language) is a query language used to navigate XML documents and select nodes based on their properties. It provides a way to locate and retrieve information from XML documents by specifying the paths to elements or attributes within the document's hierarchical structure.
XPath is like a map that helps you find specific information in a document, like an XML file. Imagine you have a big book with chapters, paragraphs, and sentences. XPath is like a guide that tells you where to look in the book to find what you need.
For example, if you're looking for a specific paragraph in a chapter, XPath would help you locate it by giving you directions like "Go to chapter 3, then find the second paragraph."
Understanding XPath Syntax
In XML documents, everything is considered a node. This includes elements, attributes, text within elements, and even the document itself. XPath uses expressions to navigate through the nodes in an XML document. These expressions are like paths that guide you to specific nodes.
For instance, let's examine the HTML snippet:
<h3 class="country-name">Andorra</h3>
Accompanied by its corresponding XPath expression:
//h3[@class='country-name']
Now, let's decipher each component of this XPath expression:
//: This double forward slash signifies a search that starts from the document's root, traversing through all hierarchy levels to find the desired node.h3: This denotes the target element we're searching for, specifically an h3 element.[@class='country-name']: Within square brackets, this signifies a condition that filters the selection based on the value of the class attribute. Here, we're looking for an h3 element with a class attribute equal to<code>country-name</code>
In summary, the XPath expression //h3[@class='country-name'] instructs XPath to locate any h3 element with a class attribute set to country-name starting from the root of the XML document, effectively guiding us to the specific node that represents the country name in the HTML snippet.
Types of XPath
XPath can be classified into different types based on how they navigate the XML document structure:
Absolute XPath
Absolute XPath expressions start with the root node of the document and traverse down the hierarchy to reach the desired element. They specify the exact location of an element in the document tree, irrespective of its context.
Here's an example:
/html/body/div[1]/form/input[2]
In this expression,/html represents the root node, followed by the path to the desired element input.
Relative XPath
Relative XPath expressions, on the other hand, rely on the context of the current node to locate elements. They offer more flexibility as they don't depend on the entire document structure but rather on the element's position relative to another element.
Here's an example:
//input[@name='username']
This expression starts anywhere in the document (//) and searches for an input element with the attribute name set to username.
Absolute XPath expressions are advantageous for tasks requiring precise targeting in stable document structures. Their direct path specification ensures accuracy, making them ideal for automated testing or scraping tasks where the document is never changed.
Relative XPath expressions offer flexibility and adaptability, making them suitable for dynamic environments where document structures may change frequently. By relying on element relationships rather than specific paths, they simplify maintenance efforts and enhance reusability across different parts of the document.
Here are some frequently used Relative XPath expressions:
| Action | Expression | Description |
| Selecting by Tag Name | //div | Selects all 'div' elements in the document. |
| Selecting by Class Name | //div[@class='container'] | Selects all 'div' elements with the class attribute equal to 'container'. |
| Selecting by ID | //*[@id='header'] | Selects the element with the ID attribute equal to 'header'. |
| Selecting by Attribute | //input[@text] | Selects all 'input' elements with the type attribute equal to 'text'. |
| Selecting by Text Content | //p[text()='Welcome'] | Selects all 'p' elements with the exact text content 'Welcome'. |
| Selecting by Partial Text Content | //a[contains(text(),'Click')] | Selects all 'a' elements whose text content contains the substring 'Click'. |
| Selecting by Position | (//ul/li)[1] | Selects the first 'li' element within any 'ul' element. |
| Selecting by Parent/Child Relationships | //div[@class='parent']/child::span | Selects all 'span' elements that are direct children of 'div' elements with the class attribute equal to 'parent'. |
| Selecting by Ancestor | //span//ancestor::div | Selects all 'div' elements that are ancestors of 'span' elements. |
| Selecting by Following-sibling | //h2/following-sibling::p | Selects all 'p' elements that are siblings following 'h2' elements. |
| Selecting by Preceding-sibling | //p[@class='info']/preceding-sibling::h2 | Selects all 'h2' elements that are siblings preceding 'p' elements with the class attribute equal to 'info'. |
Choosing Between XPath and CSS: What You Need to Know
When it comes to web scraping or automating interactions with web pages, selecting the right tool for targeting elements is crucial. Two primary methods for this purpose are XPath and CSS selectors.
Let's dive into the nuances of each and explore when to use them.
Understanding CSS Selectors
CSS selectors serve as patterns to pinpoint and style elements within HTML documents. They offer a concise syntax for identifying elements based on various criteria such as element type, class, ID, attributes, and hierarchical relationships.
Here's how you can leverage CSS selectors in your scripts:
const playwright = require("playwright");
async function getInnerText(params) {
const browser = await playwright.chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
// We insert the desired URL of the page
await page.goto("https://www.scrapethissite.com/pages/simple/");
/**
After we get the class name associated with the <h3> we want to
scrape. We will use $ function to locate the first element on the
page that matches the CSS selector
**/
// Use CSS selector to locate the desired element on the website
const element = await page.$(".country-name");
/**
Now that we have located the element that we want, we can then
display the inner text using innerText method.
**/
const innerText = await element.innerText();
console.log(innerText);
await browser.close();
}
getInnerText();
In this snippet, .country-name represents the class selector used to locate the desired element on the webpage.
Advantages of CSS Selectors:
- Concise Syntax: CSS selectors provide a readable and succinct way to target elements.
- Widespread Support: They are universally supported by modern browsers.
- Ease of Use: Developers familiar with CSS find it intuitive to work with selectors.
Understanding XPath Selectors
XPath offers a broader range of capabilities for element selection, particularly in intricate HTML structures or when elements lack convenient identifiers.
XPath expressions allow for precise targeting of elements, making them invaluable for complex scraping tasks or automated testing scenarios.
Considerations with XPath:
- Reliability: While XPath can precisely target elements, expressions relying heavily on specific paths within the HTML structure may become less reliable if the page undergoes updates or redesigns.
- Complexity: XPath expressions can be intricate and challenging to comprehend, particularly for those new to XPath.