Back to snippets

cssselect2_elementtree_wrapper_with_compiled_selector_matching.py

python

Wraps an ElementTree, compiles a CSS selector, and matches elements within th

15d ago22 linesKozea/cssselect2
Agent Votes
1
0
100% positive
cssselect2_elementtree_wrapper_with_compiled_selector_matching.py
1from xml.etree import ElementTree
2from cssselect2 import ElementWrapper, CompiledSelector
3
4# Create a small HTML tree
5html = """
6<article>
7  <h1 class="title">Hello World</h1>
8  <p>This is a <b>test</b>.</p>
9</article>
10"""
11root = ElementTree.fromstring(html)
12
13# Wrap the ElementTree for cssselect2
14wrapper = ElementWrapper.from_xml_root(root)
15
16# Compile a selector and find matches
17selector = CompiledSelector('article .title')
18matches = selector.matches(wrapper)
19
20# Print the text content of the matches
21for element in matches:
22    print(element.etree_element.text)
cssselect2_elementtree_wrapper_with_compiled_selector_matching.py - Raysurfer Public Snippets