Practical XPath Patterns for HTML Parsing in Python
Loading HTML Documents
To parse local HTML files, read the content and initialize the etree object. This sets up the DOM for traversal.
from lxml import etree
source_path = 'data/source.html'
with open(source_path, 'r', encoding='utf-8') as f:
markup = f.read()
# Create element tree from string
document = etree.HTML(markup)
Path Syntax Fundamentals
/: Selects from the root node (e.g.,/html/body/div).//: Selects nodes anywhere in the document matching the selection (e.g.,//a)..: Refers to the current node context...: Refers to the parent of the current node.
Filtering with Regular Expressions
The lxml library supports EXSLT regular expressions. This allows for complex pattern matching within XPath queries. The re:test() function is preferred for boolean checks as it is more efficient than re:match.
namespaces = {'re': 'http://exslt.org/regular-expressions'}
# Select links whose text does NOT start with 'More'
valid_links = context_node.xpath('.//a[re:test(text(), "^(?!More).*")]/text()', namespaces=namespaces)
Excluding Specific Content
To exclude nodes based on text content or attribute values, use the not() function combined with contains().
# Exclude spans containing "[...]"
clean_text = item.xpath('.//span[not(contains(text(), "[...]"))]/text()')
# Exclude anchors where the href attribute contains "logout"
nav_items = item.xpath('.//a[not(contains(@href, "logout"))]/text()')
Traversing to Ancestor Nodes
Use double dots (..) to move up the tree hierarchy. Accessing the grandparent node requires chaining the operator.
# Select 'a' tags within the grandparent of the current element
related_links = current_node.xpath('../..//a[re:test(text(), "^(?!Expand)$")]/text()', namespaces=namespaces)
Selection by ID and Class
Target specific elements using their unique identifiers or CSS classes.
# Fetch div by ID
container = document.xpath('//div[@id="main-content"]')
# Fetch all text inside divs with specific classes
description = document.xpath('//div[@class="card-body content--padded"]//text()')
Extracting Attribute Values
Retrieve specific attribute data (such as src, href, or custom data attributes) directly via XPath.
# Get the 'data-id' attribute from all list items
item_ids = document.xpath('//div[@class="listing-content"]//li/@data-id')