EN
FRENCH
繁体中文
XPath (XML Path Language) is a query language used to locate and select elements, attributes, and values within XML or HTML documents.
It describes paths through a document's hierarchical structure, making it useful for web scraping, browser automation, XML processing, and automated testing.
XPath treats a document as a tree of nodes.
A typical process includes:
XPath can select elements by tag name, attribute, position, text, or relationship to other elements.
| Expression | Meaning |
|---|---|
/ |
Selects from the root |
// |
Selects matching descendants |
@ |
Selects an attribute |
* |
Matches any element |
[ ] |
Applies a condition |
text() |
Selects text content |
For example:
//h1
selects all h1 elements.
This expression:
//div[@class='product']
selects div elements whose class attribute equals product.
XPath expressions can use absolute or relative paths.
Example:
/html/body/div/h1
is an absolute XPath.
//h1
is a relative XPath.
Relative XPath is often easier to maintain when webpage layouts change.
XPath and CSS selectors can both locate elements in HTML.
CSS selectors are convenient for straightforward element selection, while XPath can be more powerful for complex document relationships.
XPath is widely used in web scraping to extract structured information from HTML.
For example, a scraper may use XPath to locate:
Frameworks such as Scrapy and browser automation tools such as Selenium support XPath selectors directly.
Suppose a webpage contains:
<div class="product">
<h2>Wireless Mouse</h2>
<span class="price">$29.99</span>
</div>
XPath can select the product name with:
//div[@class='product']/h2/text()
The price can be selected with:
//div[@class='product']/span[@class='price']/text()
The extracted values are:
Wireless Mouse
$29.99
This allows a scraper to convert webpage content into structured product data.
XPath is a query language for locating and extracting information from XML and HTML documents.
Its ability to navigate document hierarchies and filter elements precisely makes it valuable for web scraping, automated testing, and structured data processing.
Partenariat