cssselectvsselectolax
cssselect is a BSD-licensed Python library to parse CSS3 selectors and translate them to XPath 1.0 expressions.
XPath 1.0 expressions can be used in lxml or another XPath engine to find the matching elements in an XML or HTML document.
cssselect is used by other popular Python packages like parsel
and scrapy
but can also be used on it's own to generate
valid XPath 1.0 expressions for parsing HTML and XML documents in other tools.
Note that because XPath selectors are more powerful than CSS selectors this translation is only possible one way. Converting XPath to CSS selectors is impractical and not supported by cssselect.
selectolax is a fast and lightweight library for parsing HTML and XML documents in Python. It is designed to be a drop-in replacement for the popular BeautifulSoup library, with significantly faster performance.
selectolax uses a Cython-based parser to quickly parse and navigate through HTML and XML documents. It provides a simple and intuitive API for working with the document's structure, similar to BeautifulSoup.
To use selectolax, you first need to install it via pip by running pip install selectolax``.
Once it is installed, you can use the
selectolax.html.fromstring()function to parse an HTML document and create a selectolax object.
For example:
selectolax.html.fromstring()from selectolax.parser import HTMLParser
html_string = "<html><body>Hello, World!</body></html>"
root = HTMLParser(html_string).root
print(root.tag) # html
with file-like objects, bytes or file paths,
as well as
selectolax.xml.fromstring()`` for parsing XML documents.
Once you have a selectolax object, you can use the select()
method to search for elements in the document using CSS selectors,
similar to BeautifulSoup. For example:
body = root.select("body")[0]
print(body.text()) # "Hello, World!"
Like BeautifulSoups find
and find_all
methods selectolax also supports searching using the search()`` method, which returns the first matching element,
and the
search_all()`` method, which returns all matching elements.
Example Use
from cssselect import GenericTranslator, SelectorError
translator = GenericTranslator()
try:
expression = translator.css_to_xpath('div.content')
print(expression)
'descendant-or-self::div[@class and contains(concat(' ', normalize-space(@class), ' '), ' content ')]'
except SelectorError as e:
print(f'Invalid selector {e}')
from selectolax.parser import HTMLParser
html_string = "<html><body>Hello, World!</body></html>"
root = HTMLParser(html_string).root
print(root.tag) # html
# use css selectors:
body = root.select("body")[0]
print(body.text()) # "Hello, World!"
# find first matching element:
body = root.search("body")
print(body.text()) # "Hello, World!"
# or all matching elements:
html_string = "<html><body><p>paragraph1</p><p>paragraph2</p></body></html>"
root = HTMLParser(html_string).root
for el in root.search_all("p"):
print(el.text())
# will print:
# paragraph 1
# paragraph 2