cssselect2

package
v0.26.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: BSD-3-Clause, BSD-3-Clause Imports: 8 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cssselect2 is a port of the Python package cssselect2 0.10.1, the selectors of CSS 4 for a document tree. It parses selectors from the tokens of the package tinycss2, compiles them, gives their specificity, and matches them against the elements of a tree (D50). It is public, so that ivy can port the layout of WeasyPrint, which matches its selectors with cssselect2.

How the Python types map to Go

Upstream matches an Element of xml.etree.ElementTree. In Go, a program adapts its tree to the interface Element, and wraps its root with FromXMLRoot or FromHTMLRoot, as upstream does. An HTML tree and a tree of roxmltree can both satisfy Element.

  • compile_selector_list is CompileSelectorList, and CompiledSelector is CompiledSelector. Upstream compiles each selector to Python source, and the port compiles it to closures, with the same folding of the constants 1 and 0.
  • Matcher is the generic Matcher, whose type parameter is the type of the payloads. A tuple of Matcher.match is a Match.
  • The properties of ElementWrapper are methods, such as ID, Classes, Lang and EtreeChildren. A property that can be None returns a second result of false for None.
  • A namespace prefix of None, the default namespace, is the key "" of Namespaces.
  • SelectorError wraps okage.ErrCSSSelector (D21).

Differences from upstream

The port keeps the behavior of upstream, with its faults, except for these differences (D50):

  • Where upstream raises an exception other than SelectorError for a selector, such as AttributeError, NotImplementedError or SyntaxError, the port returns a SelectorError. For example, :lang() with no argument and [*|attr] are errors.
  • The parser nests at most MaxDepth selectors in :is(), :where(), :not() and :has().
  • :local-link does not match a link whose URL makes urlparse of Python raise ValueError, where upstream raises the error.
  • Ancestors and PreviousSiblings make a new list on each call. Upstream caches a tuple of the previous siblings for each element, which takes memory in the square of the number of siblings.
  • The flag i of an attribute selector compares with strings.ToLower, where upstream uses str.lower of Python.
  • The wrappers of one tree keep the result of each relative selector of :has() for each element (D58). The results are the results of upstream, and the time of the matching is about linear in the number of elements. Upstream takes time in the square of the number of elements, and in a power of it for :has() inside :has(). Two different elements of a tree must not be equal as values of Element.
  • IterSubtree and IterChildren make the wrappers of the children of one parent as one slice. An Element with the optional method AppendChildren of ChildrenAppender gives its children without the closures of Children (D105).

Index

Constants

View Source
const MaxDepth = 32

MaxDepth is the most selectors that the parser nests in each other, with :is(), :where(), :not(), :has() and the "of" of :nth-child(). Upstream has no such limit. A deeper selector is a SelectorError (D50). The parser and the compiler recurse at each level, and a goroutine of TinyGo has a small stack, so the limit is lower than the limit of the tokenizer.

View Source
const Version = "0.10.1"

Version is VERSION of cssselect2, the version that the package ports.

Variables

This section is empty.

Functions

This section is empty.

Types

type AttributeSelector

type AttributeSelector struct {
	// Namespace is the namespace of the attribute when HasNamespace is
	// true. HasNamespace is false for any namespace, where upstream holds
	// None.
	Namespace    string
	HasNamespace bool
	// Name and LowerName are the name of the attribute.
	Name      string
	LowerName string
	// Operator is a string such as "=" or "~=" when HasOperator is true.
	// HasOperator is false for an [attr] selector, where upstream holds
	// None.
	Operator    string
	HasOperator bool
	// Value is the value to compare, when HasOperator is true.
	Value string
	// CaseSensitive is the case sensitivity of the comparison.
	CaseSensitive CaseSensitivity
}

AttributeSelector is AttributeSelector in cssselect2 cssselect2/parser.py.

func (*AttributeSelector) Specificity

func (*AttributeSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*AttributeSelector) String

func (s *AttributeSelector) String() string

String satisfies SelectorNode.

type CaseSensitivity

type CaseSensitivity int

CaseSensitivity is the attribute case_sensitive of AttributeSelector, which is True, False or None in upstream.

const (
	// CaseDocument depends on the document language. It is None.
	CaseDocument CaseSensitivity = iota
	// CaseSensitive is True, from the flag s.
	CaseSensitive
	// CaseInsensitive is False, from the flag i.
	CaseInsensitive
)

The values of CaseSensitivity.

type ChildrenAppender added in v0.23.0

type ChildrenAppender interface {
	AppendChildren(dst []Element) []Element
}

ChildrenAppender is an optional interface of an Element. AppendChildren appends the child elements to dst, in tree order, and returns the result. It skips the comments, the processing instructions and the text, as Children does. ElementWrapper calls it in place of Children when the Element has it. The iterator of Children makes closures for each element, and the list of the children then grows one element at a time (D105).

type ClassSelector

type ClassSelector struct {
	ClassName string
}

ClassSelector is ClassSelector in cssselect2 cssselect2/parser.py.

func (*ClassSelector) Specificity

func (*ClassSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*ClassSelector) String

func (s *ClassSelector) String() string

String satisfies SelectorNode.

type CombinedSelector

type CombinedSelector struct {
	// Left is a combined or a compound selector.
	Left SelectorNode
	// Combinator is " " (a single space), ">", "+" or "~".
	Combinator string
	// Right is a compound selector.
	Right *CompoundSelector
}

CombinedSelector is CombinedSelector in cssselect2 cssselect2/parser.py.

func (*CombinedSelector) Specificity

func (s *CombinedSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*CombinedSelector) String

func (s *CombinedSelector) String() string

String satisfies SelectorNode.

type CompiledSelector

type CompiledSelector struct {
	// NeverMatches is true when the selector matches no element.
	NeverMatches bool
	// Specificity is the specificity of the selector.
	Specificity Specificity
	// PseudoElement is the pseudo-element of the selector, or "".
	PseudoElement string
	// ID is the ID of the last compound selector, or "".
	ID string
	// ClassName is a class of the last compound selector, or "".
	ClassName string
	// LocalName and LowerLocalName are the type of the last compound
	// selector, or "".
	LocalName      string
	LowerLocalName string
	// Namespace is the namespace of the last compound selector, when
	// HasNamespace is true.
	Namespace    string
	HasNamespace bool
	// RequiresLangAttr is true when the last compound selector tests the
	// attribute lang.
	RequiresLangAttr bool
	// contains filtered or unexported fields
}

CompiledSelector is CompiledSelector in cssselect2 cssselect2/compiler.py, the compiled form of a selector.

func CompileSelectorList

func CompileSelectorList[T tinycss2.Input](input T, namespaces Namespaces) ([]*CompiledSelector, error)

CompileSelectorList is compile_selector_list in cssselect2 cssselect2/compiler.py. It compiles a comma-separated list of selectors.

The input is a string, or a list of component values of tinycss2, such as the Prelude of a style rule. namespaces holds the namespace prefixes in scope for the selectors. A nil namespaces declares no prefix.

func (*CompiledSelector) Test

func (c *CompiledSelector) Test(el *ElementWrapper) bool

Test is the lambda test of upstream. It reports whether el is a subject of the selector.

type CompoundSelector

type CompoundSelector struct {
	SimpleSelectors []SelectorNode
}

CompoundSelector is CompoundSelector in cssselect2 cssselect2/parser.py.

func (*CompoundSelector) Specificity

func (s *CompoundSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*CompoundSelector) String

func (s *CompoundSelector) String() string

String satisfies SelectorNode.

type Element

type Element interface {
	// Children returns the child elements, in tree order. It skips the
	// comments, the processing instructions and the text.
	Children() iter.Seq[Element]
	// LocalName returns the local name of the element.
	LocalName() string
	// NamespaceURL returns the namespace URL of the element, or "" for no
	// namespace.
	NamespaceURL() string
	// Attr returns the value of the attribute with the given namespace URL
	// and local name, and false if the element has no such attribute. The
	// namespace URL "" is no namespace. In an HTML document, cssselect2
	// asks for the lower case name.
	Attr(namespaceURL, name string) (string, bool)
	// Text returns the text before the first child element, as the
	// attribute text of ElementTree does. Only :empty reads it, and only
	// whether it is empty.
	Text() string
}

Element is an element of a document tree that selectors match. Upstream matches an Element of xml.etree.ElementTree. A program adapts its own tree to this interface, such as a tree of HTML or of roxmltree. Each value of Element must be comparable, such as a pointer or a small struct. Two values for the same element must be equal, and two values for different elements must not be, because the results of :has() are kept for each value (D58).

type ElementWrapper

type ElementWrapper struct {
	// Element is the wrapped element, the etree_element of upstream.
	Element Element
	// Parent is the wrapper of the parent, or nil for the root element.
	Parent *ElementWrapper
	// Previous is the wrapper of the previous sibling, or nil.
	Previous *ElementWrapper
	// Index is the position within the children of the parent, from 0.
	// EtreeSiblings()[Index] is always Element.
	Index int
	// InHTMLDocument is true for a wrapper of FromHTMLRoot. It makes the
	// names of the selectors case-insensitive.
	InHTMLDocument bool
	// TransportContentLanguage is the content language of the transport,
	// such as the header Content-Language of HTTP, or "".
	TransportContentLanguage string
	// contains filtered or unexported fields
}

ElementWrapper is ElementWrapper in cssselect2 cssselect2/tree.py. It wraps an Element for the matching of selectors.

Make one with FromXMLRoot or FromHTMLRoot for the root element of a document, and reach the other elements with methods such as IterChildren and IterSubtree.

func FromHTMLRoot

func FromHTMLRoot(root Element, contentLanguage string) *ElementWrapper

FromHTMLRoot is ElementWrapper.from_html_root in cssselect2 cssselect2/tree.py. It is FromXMLRoot with names that are not case sensitive. Use it for a document of an HTML parser, with the MIME type text/html.

func FromXMLRoot

func FromXMLRoot(root Element, contentLanguage string) *ElementWrapper

FromXMLRoot is ElementWrapper.from_xml_root in cssselect2 cssselect2/tree.py. It wraps the root of an XML or XHTML document.

If root is not the root of its document, the matching behaves as if it were. The selectors are not scoped to the subtree of root. contentLanguage is the content language of the transport, or "".

func (*ElementWrapper) Ancestors

func (e *ElementWrapper) Ancestors() []*ElementWrapper

Ancestors is the property ancestors of upstream: the wrappers of the ancestors, from the root to the parent.

func (*ElementWrapper) Classes

func (e *ElementWrapper) Classes() []string

Classes is the property classes of upstream: the classes of the element, with no duplicate. Upstream holds them in a set.

func (*ElementWrapper) EtreeChildren

func (e *ElementWrapper) EtreeChildren() []Element

EtreeChildren is the property etree_children of upstream: the child elements, without the other nodes such as comments and processing instructions.

func (*ElementWrapper) EtreeSiblings

func (e *ElementWrapper) EtreeSiblings() []Element

EtreeSiblings is the attribute etree_siblings of upstream: the children of the parent, or the element alone for the root.

func (*ElementWrapper) ID

func (e *ElementWrapper) ID() (string, bool)

ID is the property id of upstream: the attribute id, and false for None.

func (*ElementWrapper) InDisabledFieldset

func (e *ElementWrapper) InDisabledFieldset() bool

InDisabledFieldset is the property in_disabled_fieldset of upstream.

func (*ElementWrapper) IterChildren

func (e *ElementWrapper) IterChildren() iter.Seq[*ElementWrapper]

IterChildren is ElementWrapper.iter_children. It returns new wrappers of the child elements, in tree order.

func (*ElementWrapper) IterNextSiblings

func (e *ElementWrapper) IterNextSiblings() iter.Seq[*ElementWrapper]

IterNextSiblings is ElementWrapper.iter_next_siblings. It returns new wrappers of the next siblings of the element, in tree order.

func (*ElementWrapper) IterSiblings

func (e *ElementWrapper) IterSiblings() iter.Seq[*ElementWrapper]

IterSiblings is ElementWrapper.iter_siblings. It returns new wrappers of the siblings of the element, in tree order, with the element itself.

func (*ElementWrapper) IterSubtree

func (e *ElementWrapper) IterSubtree() iter.Seq[*ElementWrapper]

IterSubtree is ElementWrapper.iter_subtree. It returns new wrappers of the subtree of the element, in tree order, with the element itself. As in upstream, the wrappers of the children are the wrappers of IterChildren.

func (*ElementWrapper) Lang

func (e *ElementWrapper) Lang() string

Lang is the property lang of upstream: the language of the element, in ASCII lower case, or "" when it is not known. It follows http://whatwg.org/C#language.

func (*ElementWrapper) LocalName

func (e *ElementWrapper) LocalName() string

LocalName is the property local_name of upstream.

func (*ElementWrapper) Matches

func (e *ElementWrapper) Matches(selectors ...*CompiledSelector) bool

Matches is ElementWrapper.matches. It reports whether the element matches any of the given selectors. Upstream also takes the arguments of CompileSelectorList. In Go, compile them first.

func (*ElementWrapper) NamespaceURL

func (e *ElementWrapper) NamespaceURL() string

NamespaceURL is the property namespace_url of upstream.

func (*ElementWrapper) PreviousSiblings

func (e *ElementWrapper) PreviousSiblings() []*ElementWrapper

PreviousSiblings is the property previous_siblings of upstream: the wrappers of the previous siblings, in tree order.

func (*ElementWrapper) Query

func (e *ElementWrapper) Query(selectors ...*CompiledSelector) *ElementWrapper

Query is ElementWrapper.query. It returns the first element that matches any of the given selectors, or nil.

func (*ElementWrapper) QueryAll

func (e *ElementWrapper) QueryAll(selectors ...*CompiledSelector) iter.Seq[*ElementWrapper]

QueryAll is ElementWrapper.query_all. It returns the elements of the subtree, in tree order, that match any of the given selectors. The selectors are scoped to the subtree of the element.

func (*ElementWrapper) SetEtreeChildren

func (e *ElementWrapper) SetEtreeChildren(children []Element)

SetEtreeChildren sets the cached property etree_children, as WeasyPrint does for the elements of SVG that it makes. It drops the results of :has() that the wrappers of the tree keep (D58).

type FunctionalPseudoClassSelector

type FunctionalPseudoClassSelector struct {
	Name      string
	Arguments []tinycss2.Node
}

FunctionalPseudoClassSelector is FunctionalPseudoClassSelector in cssselect2 cssselect2/parser.py.

func (*FunctionalPseudoClassSelector) Specificity

Specificity satisfies SelectorNode.

func (*FunctionalPseudoClassSelector) String

String satisfies SelectorNode.

type IDSelector

type IDSelector struct {
	Ident string
}

IDSelector is IDSelector in cssselect2 cssselect2/parser.py.

func (*IDSelector) Specificity

func (*IDSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*IDSelector) String

func (s *IDSelector) String() string

String satisfies SelectorNode.

type LocalNameSelector

type LocalNameSelector struct {
	LocalName      string
	LowerLocalName string
}

LocalNameSelector is LocalNameSelector in cssselect2 cssselect2/parser.py.

func (*LocalNameSelector) Specificity

func (*LocalNameSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*LocalNameSelector) String

func (s *LocalNameSelector) String() string

String satisfies SelectorNode.

type Match

type Match[P any] struct {
	Specificity   Specificity
	Order         int
	PseudoElement string
	Payload       P
}

Match is a tuple of the result of Matcher.match in upstream: the specificity, the order, the pseudo-element and the payload of a selector that matches.

type Matcher

type Matcher[P any] struct {
	// contains filtered or unexported fields
}

Matcher is Matcher in cssselect2 cssselect2/__init__.py, a store of CSS selectors that matches HTML elements. P is the type of the payloads, such as the declarations of a style rule.

func NewMatcher

func NewMatcher[P any]() *Matcher[P]

NewMatcher makes an empty Matcher.

func (*Matcher[P]) AddSelector

func (m *Matcher[P]) AddSelector(selector *CompiledSelector, payload P)

AddSelector is Matcher.add_selector. It adds a selector and its payload to the matcher. Match returns the payload as it is.

func (*Matcher[P]) AppendMatches added in v0.12.0

func (m *Matcher[P]) AppendMatches(dst []Match[P], element *ElementWrapper) []Match[P]

AppendMatches appends the result of Match to dst, and returns the extended slice. Upstream does not have it. A program that reuses dst for each element does not allocate a slice for each element (D61).

func (*Matcher[P]) Match

func (m *Matcher[P]) Match(element *ElementWrapper) []Match[P]

Match is Matcher.match. It matches the selectors against the given element.

It returns the selectors that match the element, from the lowest to the highest specificity, and in the order of AddSelector for an equal specificity.

type MatchesAnySelector

type MatchesAnySelector struct {
	SelectorList []*Selector
}

MatchesAnySelector is MatchesAnySelector in cssselect2 cssselect2/parser.py, for :is().

func (*MatchesAnySelector) Specificity

func (s *MatchesAnySelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*MatchesAnySelector) String

func (s *MatchesAnySelector) String() string

String satisfies SelectorNode.

type NamespaceSelector

type NamespaceSelector struct {
	// Namespace is the namespace URL, or the empty string for elements in
	// no namespace.
	Namespace string
}

NamespaceSelector is NamespaceSelector in cssselect2 cssselect2/parser.py.

func (*NamespaceSelector) Specificity

func (*NamespaceSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*NamespaceSelector) String

func (s *NamespaceSelector) String() string

String satisfies SelectorNode.

type Namespaces

type Namespaces map[string]string

Namespaces maps the namespace prefixes that are in scope for a selector to their namespace URLs. The key "" is the default namespace, which is the key None of upstream.

type NegationSelector

type NegationSelector struct {
	SelectorList []*Selector
}

NegationSelector is NegationSelector in cssselect2 cssselect2/parser.py, for :not().

func (*NegationSelector) Specificity

func (s *NegationSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*NegationSelector) String

func (s *NegationSelector) String() string

String satisfies SelectorNode.

type PseudoClassSelector

type PseudoClassSelector struct {
	Name string
}

PseudoClassSelector is PseudoClassSelector in cssselect2 cssselect2/parser.py.

func (*PseudoClassSelector) Specificity

func (*PseudoClassSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*PseudoClassSelector) String

func (s *PseudoClassSelector) String() string

String satisfies SelectorNode.

type RelationalSelector

type RelationalSelector struct {
	SelectorList []*Selector
}

RelationalSelector is RelationalSelector in cssselect2 cssselect2/parser.py, for :has(). Each selector of its list is relative.

func (*RelationalSelector) Specificity

func (s *RelationalSelector) Specificity() Specificity

Specificity satisfies SelectorNode.

func (*RelationalSelector) String

func (s *RelationalSelector) String() string

String satisfies SelectorNode.

type Selector

type Selector struct {
	// ParsedTree is the tree of the selector.
	ParsedTree SelectorNode
	// PseudoElement is the pseudo-element of the selector, or "" for None.
	PseudoElement string
	// Specificity is the specificity of the selector.
	Specificity Specificity
	// Combinator is the combinator of a RelativeSelector: " ", ">", "+" or
	// "~". It is "" for a selector that is not relative.
	Combinator string
}

Selector is Selector in cssselect2 cssselect2/parser.py, a parsed selector, and also RelativeSelector of the same file, which has a combinator.

func Parse

func Parse[T tinycss2.Input](input T, namespaces Namespaces, forgiving, relative bool) ([]*Selector, error)

Parse is parse in cssselect2 cssselect2/parser.py. It parses the selectors of a comma-separated list. The input is a string or a list of component values of tinycss2.

If forgiving is true, an invalid selector is dropped, and Parse returns no error. If relative is true, each selector can start with a combinator, as in :has().

func (*Selector) String

func (s *Selector) String() string

String is Selector.__repr__, or RelativeSelector.__repr__.

type SelectorError

type SelectorError struct {
	// Token is the token of the error, or nil.
	Token tinycss2.Node
	// Message is the message of upstream.
	Message string
}

SelectorError is SelectorError in cssselect2 cssselect2/parser.py, the error of an invalid or unsupported selector. It wraps okage.ErrCSSSelector, so that errors.Is finds it (D21).

The port also returns it where upstream raises another exception for a selector, such as AttributeError, NotImplementedError or SyntaxError, so that no stylesheet makes it panic (D50).

func (*SelectorError) Error

func (e *SelectorError) Error() string

Error satisfies the error interface.

func (*SelectorError) Unwrap

func (e *SelectorError) Unwrap() error

Unwrap returns okage.ErrCSSSelector.

type SelectorNode

type SelectorNode interface {
	// Specificity is the attribute specificity of upstream.
	Specificity() Specificity
	// String is the __repr__ of upstream.
	String() string
}

SelectorNode is a node of the tree of a parsed selector: one of the selector classes of cssselect2 cssselect2/parser.py.

type Specificity

type Specificity [3]int

Specificity is the specificity of a selector: three integers, as http://www.w3.org/TR/selectors/#specificity says.

func (Specificity) Compare

func (s Specificity) Compare(other Specificity) int

Compare compares two specificities in the order of a Python tuple. It returns -1, 0 or 1.

type SpecificityAdjustmentSelector

type SpecificityAdjustmentSelector struct {
	SelectorList []*Selector
}

SpecificityAdjustmentSelector is SpecificityAdjustmentSelector in cssselect2 cssselect2/parser.py, for :where().

func (*SpecificityAdjustmentSelector) Specificity

Specificity satisfies SelectorNode.

func (*SpecificityAdjustmentSelector) String

String satisfies SelectorNode.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL