Skip to main content

A collection of utility functions for working with lxml and XPath.

Supports Python 2+.

Functions

  • inner_text(element: ElementBase) -> str: Extracts the combined text content of an element and its descendants, like accessing JavaScript's innerText attribute.
  • find_deepest_elements_containing_target_text(element: ElementBase, target_text: str) -> Iterator[ElementBase]: A generator that yields the deepest elements containing target text, starting from leaf nodes.
  • get_xpath(element: ElementBase, relative_to: Optional[ElementBase] = None) -> str: Generates the absolute or relative XPath expression for a given lxml element. If relative_to is specified, the XPath will be relative to that element.

Usage

Here's a brief example of how to use the functions:

from __future__ import print_function

from lxml import etree

from lxml_xpath_utils import inner_text, find_deepest_elements_containing_target_text, get_xpath

html = """<html>
    <body>
        <div id="main">
            <p>This is a paragraph with target text.</p>
            <div class="nested">
                <span>Some text here</span>
                <p>Another paragraph with target text in it.</p>
            </div>
            <p>No match here</p>
        </div>
        <div id="other">
            <p>target text appears again here</p>
        </div>
    </body>
</html>"""

target_text = "target text"

parser = etree.HTMLParser()
root = etree.fromstring(html, parser)

matching_elements = find_deepest_elements_containing_target_text(root, target_text)

print("Elements containing '%s':" % target_text)
for elem in matching_elements:
    absolute_xpath = get_xpath(elem)
    print(absolute_xpath)
    assert elem == root.xpath(absolute_xpath)[0]
    print("  Text: %s\n" % inner_text(elem))

print("Elements containing '%s' in /html/body/div[@id='main']:" % target_text)
new_root = root.xpath('/html/body/div[@id="main"]')[0]
new_matching_elements = find_deepest_elements_containing_target_text(new_root, target_text)

for new_elem in new_matching_elements:
    relative_xpath = get_xpath(new_elem, new_root)
    print(relative_xpath)
    assert new_elem == new_root.xpath(relative_xpath)[0]
    print("  Text: %s\n" % inner_text(new_elem))

Output:

Elements containing 'target text':
/html/body/div[1]/p[1]
  Text: This is a paragraph with target text.

/html/body/div[1]/div/p
  Text: Another paragraph with target text in it.

/html/body/div[2]/p
  Text: target text appears again here

Elements containing 'target text' in /html/body/div[@id='main']:
./p[1]
  Text: This is a paragraph with target text.

./div/p
  Text: Another paragraph with target text in it.

Contributing

Feel free to contribute to this project by submitting pull requests or opening issues.

License

This project is licensed under the MIT License.

Release files for lxml-xpath-utils 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for lxml-xpath-utils 0.1.1
File Size Uploaded
lxml_xpath_utils-0.1.1.tar.gz 3.7 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for lxml-xpath-utils 0.1.1
File Interpreter ABI Platform
lxml_xpath_utils-0.1.1-py2.py3-none-any.whl Python 3, Python 2 none any Details

Total release size: 7.7 kB

Release files / lxml_xpath_utils-0.1.1.tar.gz

Download URL lxml_xpath_utils-0.1.1.tar.gz
Size 3.7 kB
Tags Source
SHA-256 checksum
How to use checksums
3ddc77c5b56c593040c197dc5027a6e553ef1bba1e9498ba43970493d0582f0d
BLAKE2b-256 checksum
How to use checksums
008b4882602dfba5edee901c6bfd802bc727d8a263bf034db1bbbce7fec33747
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.2

Release files / lxml_xpath_utils-0.1.1-py2.py3-none-any.whl

Download URL lxml_xpath_utils-0.1.1-py2.py3-none-any.whl
Size 4.1 kB
Tags Python 2 Python 3
SHA-256 checksum
How to use checksums
042e22565bc65ac1a4c610ce453721f77e6c865c79922b50d0549e9d4013a450
BLAKE2b-256 checksum
How to use checksums
c57cc98b0ef7d7a0977bc931c4b1642364e3a90bc0ab842fdb4b7134600e8057
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.12.2

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page