Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Practical XPath Patterns for HTML Parsing in Python

Tech Nov 16 15

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')
Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.