Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/soupsieve/css_match.py: 65%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""CSS matcher."""
2from __future__ import annotations
3from bisect import bisect_right
4from datetime import datetime
5from math import isfinite
6from collections.abc import Hashable
7from . import bidi
8from . import util
9import re
10from . import css_types as ct
11import bs4
12from typing import (
13 Generator,
14 Iterator,
15 Iterable,
16 Any,
17 Callable,
18 Sequence,
19 overload,
20 Literal,
21 NamedTuple,
22 cast,
23 TYPE_CHECKING
24) # noqa: F401, F811
26# Empty tag pattern (whitespace okay)
27RE_NOT_EMPTY = re.compile('[^ \t\r\n\f]')
29RE_NOT_WS = re.compile('[^ \t\r\n\f]+')
31# Relationships
32REL_PARENT = ' '
33REL_CLOSE_PARENT = '>'
34REL_SIBLING = '~'
35REL_CLOSE_SIBLING = '+'
37# Relationships for :has() (forward looking)
38REL_HAS_PARENT = ': '
39REL_HAS_CLOSE_PARENT = ':>'
40REL_HAS_SIBLING = ':~'
41REL_HAS_CLOSE_SIBLING = ':+'
43# `bs4` imports this module while it is still initializing,
44# so these must only be evaluated when type checking.
45if TYPE_CHECKING: # pragma: no cover
46 MatchRequest = tuple[bs4.Tag, ct.SelectorList]
47 MatchGenerator = Generator[MatchRequest, bool, bool]
49NS_XHTML = 'http://www.w3.org/1999/xhtml'
50NS_XML = 'http://www.w3.org/XML/1998/namespace'
51NS_SVG = 'http://www.w3.org/2000/svg'
53# Values of `type` that put an `input` in a state that does not use its value for `dir="auto"`.
54# A missing or invalid value is the Text state, which does.
55NON_AUTO_DIR_INPUT_TYPES = frozenset((
56 'date', 'month', 'week', 'time', 'datetime-local', 'number', 'range', 'color', 'checkbox',
57 'radio', 'file', 'image'
58))
60# HTML elements whose text is ignored when resolving `dir="auto"` on an ancestor.
61AUTO_DIR_IGNORED_ELEMENTS = frozenset(('bdi', 'script', 'style', 'textarea'))
63DIR_FLAGS = ct.SEL_DIR_LTR | ct.SEL_DIR_RTL
64RANGES = ct.SEL_IN_RANGE | ct.SEL_OUT_OF_RANGE
66DIR_MAP = {
67 'ltr': ct.SEL_DIR_LTR,
68 'rtl': ct.SEL_DIR_RTL,
69 'auto': 0
70}
72RE_NUM = re.compile(r"^(?P<value>-?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?)\Z")
73RE_TIME = re.compile(r'^(?P<hour>[0-9]{2}):(?P<minutes>[0-9]{2})(?::(?P<seconds>[0-9]{2}(?:\.[0-9]{1,3})?))?\Z')
74RE_MONTH = re.compile(r'^(?P<year>[0-9]{4,})-(?P<month>[0-9]{2})\Z')
75RE_WEEK = re.compile(r'^(?P<year>[0-9]{4,})-W(?P<week>[0-9]{2})\Z')
76RE_DATE = re.compile(r'^(?P<year>[0-9]{4,})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})\Z')
77RE_DATETIME = re.compile(
78 r'^(?P<year>[0-9]{4,})-(?P<month>[0-9]{2})-(?P<day>[0-9]{2})[T ](?P<hour>[0-9]{2}):(?P<minutes>[0-9]{2})'
79 r'(?::(?P<seconds>[0-9]{2}(?:\.[0-9]{1,3})?))?\Z'
80)
81RE_SIZE = re.compile(r'[ \t\r\n\f]*\+?(?P<value>[0-9]+)')
82# BCP 47 syntax for an extended language range (RFC 4647) and a language tag (RFC 5646), as browsers check it:
83# subtags of 1 to 8 ASCII letters and digits, the first only letters, and `*` subtags only in a range.
84# Subtags are not checked against the registry.
85RE_LANG_RANGE = re.compile(r'(?:[a-zA-Z]{1,8}|\*)(?:-(?:[a-zA-Z0-9]{1,8}|\*))*')
86RE_LANG_TAG = re.compile(r'[a-zA-Z]{1,8}(?:-[a-zA-Z0-9]{1,8})*')
88MONTHS_30 = (4, 6, 9, 11) # April, June, September, and November
89FEB = 2
90SHORT_MONTH = 30
91LONG_MONTH = 31
92FEB_MONTH = 28
93FEB_LEAP_MONTH = 29
95# The latest value each date and time input type accepts in browsers. The HTML spec puts no upper
96# limit on the year, but browsers store these values as a JavaScript time, which ends at
97# 275760-09-13T00:00:00Z, and reject a value whose period starts after it. Chrome, Firefox and
98# Safari agree on `date` and `datetime-local`; Chrome is the only one with `month` and `week`.
99MAX_INPUT_VALUE: dict[str, tuple[float, ...]] = {
100 'date': (275760, 9, 13),
101 'month': (275760, 9),
102 'week': (275760, 37),
103 'datetime-local': (275760, 9, 13, 0, 0, 0),
104}
105DAYS_IN_WEEK = 7
108class NthState:
109 """Lazily built positions of the siblings counted by an `nth` selector under one parent."""
111 __slots__ = ('pos', 'count', 'positions', 'counts')
113 def __init__(
114 self,
115 pos: int,
116 count: int,
117 positions: dict[int, int],
118 counts: dict[tuple[str | None, str], int] | None
119 ) -> None:
120 """Initialize."""
122 # Next position in the parent's contents to scan
123 self.pos = pos
124 # Number of counted siblings found so far
125 self.count = count
126 # 1-based index of each counted sibling, keyed by `id()`, among the siblings of its type for `of-type`
127 self.positions = positions
128 # For `of-type`, the number of siblings found so far of each type, keyed by tag name and namespace,
129 # so siblings of every type share one scan, and `None` otherwise
130 self.counts = counts
133class TreeForms(NamedTuple):
134 """The form information of a tree. Elements are tracked by `id()` as `bs4` hashes them by their content."""
136 # The form owner of each `input` and `button`
137 owners: dict[int, bs4.Tag | None]
138 # The default button of each form
139 defaults: dict[int, bs4.Tag]
140 # The last radio button with a `checked` attribute of each radio button group, by form owner and name
141 checked: dict[tuple[int, str], bs4.Tag]
144def uses_scope(selectors: ct.SelectorList) -> bool:
145 """Check if any part of a selector, nested ones included, matches the scope (`:scope` or `&`)."""
147 seen: set[int] = set()
148 stack = [selectors]
149 while stack:
150 selector_list = stack.pop()
151 if id(selector_list) in seen:
152 continue
153 seen.add(id(selector_list))
154 for selector in selector_list:
155 if isinstance(selector, ct.SelectorNull):
156 continue
157 if selector.flags & ct.SEL_SCOPE:
158 return True
159 stack.extend(selector.selectors)
160 stack.append(selector.relation)
161 stack.extend(nth.selectors for nth in selector.nth)
162 return False
165class _DocumentNav:
166 """Navigate a Beautiful Soup document."""
168 @classmethod
169 def assert_valid_input(cls, tag: Any) -> None:
170 """Check if valid input tag or document."""
172 # Fail on unexpected types.
173 if not cls.is_tag(tag):
174 raise TypeError(f"Expected a BeautifulSoup 'Tag', but instead received type {type(tag)}")
176 @staticmethod
177 def is_doc(obj: bs4.element.PageElement | None) -> bool:
178 """Is `BeautifulSoup` object."""
179 return isinstance(obj, bs4.BeautifulSoup)
181 @staticmethod
182 def is_tag(obj: bs4.element.PageElement | None) -> bool:
183 """Is tag."""
184 return isinstance(obj, bs4.Tag)
186 @staticmethod
187 def is_declaration(obj: bs4.element.PageElement | None) -> bool: # pragma: no cover
188 """Is declaration."""
189 return isinstance(obj, bs4.Declaration)
191 @staticmethod
192 def is_cdata(obj: bs4.element.PageElement | None) -> bool:
193 """Is CDATA."""
194 return isinstance(obj, bs4.CData)
196 @staticmethod
197 def is_processing_instruction(obj: bs4.element.PageElement | None) -> bool: # pragma: no cover
198 """Is processing instruction."""
199 return isinstance(obj, bs4.ProcessingInstruction)
201 @staticmethod
202 def is_navigable_string(obj: bs4.element.PageElement | None) -> bool:
203 """Is navigable string."""
204 return isinstance(obj, bs4.element.NavigableString)
206 @staticmethod
207 def is_special_string(obj: bs4.element.PageElement | None) -> bool:
208 """Is special string."""
209 return isinstance(obj, (bs4.Comment, bs4.Declaration, bs4.CData, bs4.ProcessingInstruction, bs4.Doctype))
211 @classmethod
212 def is_content_string(cls, obj: bs4.element.PageElement | None) -> bool:
213 """Check if node is content string."""
215 return cls.is_navigable_string(obj) and not cls.is_special_string(obj)
217 @staticmethod
218 def is_xml_tree(el: bs4.Tag | None) -> bool:
219 """Check if element (or document) is from a XML tree."""
221 return el is not None and bool(el._is_xml)
223 def is_template(self, el: bs4.Tag) -> bool:
224 """
225 Check if element is an HTML `template`.
227 The contents of a `template` are not part of the document, so navigation stops at one in both directions.
228 This is called for every element that is navigated, so avoid normalizing names that can't match.
229 """
231 if len(el.name) != 8:
232 return False
234 return bool(
235 ((el.name if self.is_xml_tree(el) else util.lower(el.name)) == 'template') and
236 self.is_html_tag(el) # type: ignore[attr-defined]
237 )
239 def is_root(self, el: bs4.Tag) -> bool:
240 """Return whether element is the root of the tree (which we have already pre-calculated)."""
242 return bool(self.root and self.root is el) # type: ignore[attr-defined]
244 def has_contents(self, el: bs4.Tag | None, template_contents: bool) -> bool:
245 """Check if the contents of an element should be navigated."""
247 return el is not None and (template_contents or not self.is_template(el))
249 def get_contents(
250 self,
251 el: bs4.Tag | None,
252 template_contents: bool = False
253 ) -> Iterator[bs4.element.PageElement]:
254 """Get contents or contents in reverse."""
256 if self.has_contents(el, template_contents):
257 yield from cast('bs4.Tag', el).contents
259 def get_tag_children(
260 self,
261 el: bs4.Tag | None,
262 start: int | None = None,
263 reverse: bool = False
264 ) -> Iterator[bs4.Tag]:
265 """Get tag children."""
267 return self.get_children(el, start, reverse, True)
269 @overload
270 def get_children(
271 self,
272 el: bs4.Tag | None,
273 start: int | None = None,
274 reverse: bool = False,
275 tags: Literal[True] = ...,
276 template_contents: bool = False
277 ) -> Iterator[bs4.Tag]:
278 ...
280 @overload
281 def get_children(
282 self,
283 el: bs4.Tag | None,
284 start: int | None = None,
285 reverse: bool = False,
286 tags: Literal[False] = ...,
287 template_contents: bool = False
288 ) -> Iterator[bs4.element.PageElement]:
289 ...
291 def get_children(
292 self,
293 el: bs4.Tag | None,
294 start: int | None = None,
295 reverse: bool = False,
296 tags: Literal[True] | Literal[False] = False,
297 template_contents: bool = False
298 ) -> Iterator[bs4.element.PageElement]:
299 """Get children."""
301 if el is not None and self.has_contents(el, template_contents):
302 last = len(el.contents) - 1
303 if start is None:
304 index = last if reverse else 0
305 else:
306 index = start
307 end = -1 if reverse else last + 1
308 incr = -1 if reverse else 1
310 if 0 <= index <= last:
311 for i in range(index, end, incr):
312 node = el.contents[i]
313 if not tags or self.is_tag(node):
314 yield node
316 def get_tag_descendants(
317 self,
318 el: bs4.Tag | None,
319 template_contents: bool = False
320 ) -> Iterator[bs4.Tag]:
321 """Specifically get tag descendants."""
323 yield from self.get_descendants( # type: ignore[misc]
324 el, tags=True, template_contents=template_contents
325 )
327 def get_descendants(
328 self,
329 el: bs4.Tag | None,
330 tags: bool = False,
331 template_contents: bool = False
332 ) -> Iterator[bs4.element.PageElement]:
333 """
334 Get descendants.
336 `template_contents` only allows entering `el`, any `template` found within it is still not entered.
337 """
339 if el is not None and self.has_contents(el, template_contents):
340 next_good = None
341 for child in el.descendants:
343 if next_good is not None:
344 if child is not next_good:
345 continue
346 next_good = None
348 if isinstance(child, bs4.Tag):
349 if self.is_template(child):
350 if child.next_sibling is not None:
351 next_good = child.next_sibling
352 else:
353 last_child: bs4.element.PageElement = child
354 while isinstance(last_child, bs4.Tag) and last_child.contents:
355 last_child = last_child.contents[-1]
356 next_good = last_child.next_element
357 yield child
358 if next_good is None:
359 break
360 # Coverage isn't seeing this even though it's executed
361 continue # pragma: no cover
362 yield child
364 elif not tags:
365 yield child
367 def get_parent(
368 self,
369 el: bs4.Tag | None,
370 no_doc: bool = True,
371 no_template: bool = True
372 ) -> bs4.Tag | None:
373 """Get parent."""
375 parent = el.parent if el is not None else None
376 if no_template and parent is not None and self.is_template(parent):
377 parent = None
378 if no_doc and self.is_doc(parent):
379 parent = None
380 return parent
382 @staticmethod
383 def get_tag_name(el: bs4.Tag | None) -> str | None:
384 """Get tag."""
386 return el.name if el is not None else None
388 @staticmethod
389 def get_prefix_name(el: bs4.Tag) -> str | None:
390 """Get prefix."""
392 return el.prefix
394 @staticmethod
395 def get_uri(el: bs4.Tag | None) -> str | None:
396 """Get namespace `URI`."""
398 return el.namespace if el is not None else None
400 @classmethod
401 def get_next_tag(cls, el: bs4.Tag) -> bs4.Tag | None:
402 """Get next sibling tag."""
404 return cls.get_next(el, tags=True) # type: ignore[return-value]
406 @classmethod
407 def get_next(cls, el: bs4.Tag, tags: bool = False) -> bs4.element.PageElement | None:
408 """Get next sibling tag."""
410 sibling = el.next_sibling
411 while tags and not isinstance(sibling, bs4.Tag) and sibling is not None:
412 sibling = sibling.next_sibling
414 if tags and not isinstance(sibling, bs4.Tag):
415 sibling = None
417 return sibling
419 @classmethod
420 def get_previous_tag(cls, el: bs4.Tag, tags: bool = True) -> bs4.Tag | None:
421 """Get previous sibling tag."""
423 return cls.get_previous(el, True) # type: ignore[return-value]
425 @classmethod
426 def get_previous(cls, el: bs4.Tag, tags: bool = False) -> bs4.element.PageElement | None:
427 """Get previous sibling tag."""
429 sibling = el.previous_sibling
430 while tags and not isinstance(sibling, bs4.Tag) and sibling is not None:
431 sibling = sibling.previous_sibling
433 if tags and not isinstance(sibling, bs4.Tag):
434 sibling = None
436 return sibling
438 @staticmethod
439 def has_html_ns(el: bs4.Tag | None) -> bool:
440 """
441 Check if element has an HTML namespace.
443 This is a bit different than whether a element is treated as having an HTML namespace,
444 like we do in the case of `is_html_tag`.
445 """
447 ns = getattr(el, 'namespace') if el is not None else None # noqa: B009
448 return bool(ns and ns == NS_XHTML)
450 @staticmethod
451 def split_namespace(el: bs4.Tag | None, attr_name: str) -> tuple[str | None, str | None]:
452 """Return namespace and attribute name without the prefix."""
454 if el is None: # pragma: no cover
455 return None, None
457 return getattr(attr_name, 'namespace', None), getattr(attr_name, 'name', None)
459 @classmethod
460 def get_attribute_by_name(
461 cls,
462 el: bs4.Tag,
463 name: str,
464 default: str | Sequence[str] | None = None
465 ) -> str | Sequence[str] | None:
466 """Get attribute by name."""
468 value = default
469 if el._is_xml:
470 if name in el.attrs:
471 v = el.attrs[name]
472 value = '' if v is None else v
473 else:
474 for k, v in el.attrs.items():
475 if util.lower(k) == name:
476 value = '' if v is None else v
477 break
478 return value
480 @classmethod
481 def iter_attributes(cls, el: bs4.Tag | None) -> Iterator[tuple[str, str | Sequence[str] | None]]:
482 """Iterate attributes."""
484 if el is not None:
485 for k, v in el.attrs.items():
486 yield k, '' if v is None else v
488 @classmethod
489 def get_classes(cls, el: bs4.Tag) -> Sequence[str]:
490 """Get classes."""
492 classes = cls.get_attribute_by_name(el, 'class', [])
493 if isinstance(classes, str):
494 classes = RE_NOT_WS.findall(classes)
495 return cast(Sequence[str], classes)
497 def get_text(self, el: bs4.Tag) -> str:
498 """Get text."""
500 return ''.join(
501 [
502 node for node in self.get_descendants(el) # type: ignore[misc]
503 if self.is_content_string(node)
504 ]
505 )
507 def get_own_text(self, el: bs4.Tag) -> list[str]:
508 """Get Own Text."""
510 return [
511 node for node in self.get_contents(el) if self.is_content_string(node) # type: ignore[misc]
512 ]
515class Inputs:
516 """Class for parsing and validating input items."""
518 @staticmethod
519 def validate_day(year: int, month: int, day: int) -> bool:
520 """Validate day."""
522 max_days = LONG_MONTH
523 if month == FEB:
524 max_days = FEB_LEAP_MONTH if ((year % 4 == 0) and (year % 100 != 0)) or (year % 400 == 0) else FEB_MONTH
525 elif month in MONTHS_30:
526 max_days = SHORT_MONTH
527 return 1 <= day <= max_days
529 @staticmethod
530 def validate_week(year: int, week: int) -> bool:
531 """Validate week."""
533 # Validate an ISO week number for `year`.
534 #
535 # Per ISO 8601 rules, the last ISO week of a year is the week
536 # containing Dec 28. Using Dec 28 guarantees we obtain the
537 # correct ISO week-number for the final week of `year`, even in
538 # years where Dec 31 falls in ISO week 01 of the following year.
539 #
540 # Example: if Dec 31 is a Thursday the year's last ISO week will
541 # be week 53; if Dec 31 is a Monday and that week is counted as
542 # week 1 of the next year, Dec 28 still belongs to the final
543 # week of the current ISO year and yields the correct max week.
544 #
545 # `datetime` stops at year 9999, but the calendar repeats every 400
546 # years (a whole number of weeks), so use the matching year from 2000
547 # to 2399, as `calendar.weekday()` does.
548 max_week = datetime(2000 + year % 400, 12, 28).isocalendar()[1]
549 return 1 <= week <= max_week
551 @staticmethod
552 def validate_month(month: int) -> bool:
553 """Validate month."""
555 return 1 <= month <= 12
557 @staticmethod
558 def validate_year(year: int) -> bool:
559 """Validate year."""
561 return 1 <= year
563 @staticmethod
564 def parse_year(year: str) -> int:
565 """
566 Parse year.
568 A year is four or more digits with no upper limit, but `int()` refuses digit strings longer than
569 `sys.get_int_max_str_digits()`, so treat a year that long as invalid.
570 """
572 try:
573 return int(year, 10)
574 except ValueError:
575 return 0
577 @staticmethod
578 def validate_hour(hour: int) -> bool:
579 """Validate hour."""
581 return 0 <= hour <= 23
583 @staticmethod
584 def validate_minutes(minutes: int) -> bool:
585 """Validate minutes."""
587 return 0 <= minutes <= 59
589 @staticmethod
590 def validate_seconds(seconds: float) -> bool:
591 """Validate seconds."""
593 return 0 <= seconds < 60
595 @classmethod
596 def parse_value(cls, itype: str, value: str | None) -> tuple[float, ...] | None:
597 """
598 Parse an input's `value`, `min` or `max` attribute, returning `None` if it is not valid.
600 The same strict syntax is used for all three attributes, which is what browsers do. The HTML
601 spec only requires it for the value. It converts `min` and `max` with more lenient algorithms,
602 but every browser rejects what only those algorithms accept:
604 - `number` and `range`: the spec's "rules for parsing floating-point number values" skip
605 leading whitespace, accept a leading `+`, and ignore trailing characters (`20abc`, `20.`,
606 `2e+`). Browsers reject all of these, so a `min` or `max` must be a valid floating-point
607 number. A number that overflows a double (`1e9999`) is an error in the spec too.
608 - `time` and `datetime-local`: the spec's parser accepts any number of fractional second
609 digits, but browsers reject more than three, as in a valid time string.
610 - `date`, `month`, `week` and `datetime-local`: the spec has no upper limit on the year,
611 but browsers reject a value after `MAX_INPUT_VALUE`.
613 Dates and times need the whole string to match, with no surrounding whitespace, a year of four
614 or more digits greater than zero, an upper-case `W` in a week, and a `T` or a single space
615 between the date and time of a `datetime-local`. Browsers and the spec agree on these.
616 """
618 parsed: tuple[float, ...] | None = None
619 if value is None:
620 return value
621 if itype == "date":
622 m = RE_DATE.match(value)
623 if m:
624 year = cls.parse_year(m.group('year'))
625 month = int(m.group('month'), 10)
626 day = int(m.group('day'), 10)
627 if cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day):
628 parsed = (year, month, day)
629 elif itype == "month":
630 m = RE_MONTH.match(value)
631 if m:
632 year = cls.parse_year(m.group('year'))
633 month = int(m.group('month'), 10)
634 if cls.validate_year(year) and cls.validate_month(month):
635 parsed = (year, month)
636 elif itype == "week":
637 m = RE_WEEK.match(value)
638 if m:
639 year = cls.parse_year(m.group('year'))
640 week = int(m.group('week'), 10)
641 if cls.validate_year(year) and cls.validate_week(year, week):
642 parsed = (year, week)
643 elif itype == "time":
644 m = RE_TIME.match(value)
645 if m:
646 hour = int(m.group('hour'), 10)
647 minutes = int(m.group('minutes'), 10)
648 seconds = float(m.group('seconds') or 0)
649 if cls.validate_hour(hour) and cls.validate_minutes(minutes) and cls.validate_seconds(seconds):
650 parsed = (hour, minutes, seconds)
651 elif itype == "datetime-local":
652 m = RE_DATETIME.match(value)
653 if m:
654 year = cls.parse_year(m.group('year'))
655 month = int(m.group('month'), 10)
656 day = int(m.group('day'), 10)
657 hour = int(m.group('hour'), 10)
658 minutes = int(m.group('minutes'), 10)
659 seconds = float(m.group('seconds') or 0)
660 if (
661 cls.validate_year(year) and cls.validate_month(month) and cls.validate_day(year, month, day) and
662 cls.validate_hour(hour) and cls.validate_minutes(minutes) and cls.validate_seconds(seconds)
663 ):
664 parsed = (year, month, day, hour, minutes, seconds)
665 elif itype in ("number", "range"):
666 m = RE_NUM.match(value)
667 if m:
668 number = float(m.group('value'))
669 if isfinite(number):
670 parsed = (number,)
671 if parsed is not None and itype in MAX_INPUT_VALUE and parsed > MAX_INPUT_VALUE[itype]:
672 parsed = None
673 return parsed
676class CSSMatch(_DocumentNav):
677 """
678 Perform CSS matching.
680 Performance contract: for a given selector, the time to match a document grows linearly with the size of
681 the document, whatever its shape: deeply nested, very wide, or with many top level elements. Before
682 changing how something is matched, check that it stays linear on such documents, and when a cache is needed
683 for that, follow the rules for caches in `__init__()`.
685 Within that, these are expected and are not bugs:
687 - Time proportional to the size of the selector times the size of the document. Every element may be
688 checked against every part of the selector, so a long selector costs more. This includes a long chain
689 of combinators, such as `p ~ p ~ ... ~ p` with `k` links, which takes time proportional to `k` squared
690 on a parent with at least `k` children, as each child walks up to `k` links: that is still at most the
691 size of the selector times the size of the document.
692 - Time proportional to the length of an attribute value or a text, as with any string search.
693 - Anything with `NOCACHE`, which turns off the caches that keep matching linear and is documented as
694 possibly slow, and the complex `:has()` forms that `NOSTRICT` allows, which are documented likewise.
695 - Matching the elements of a document one call at a time, such as calling `match()` for each element in
696 a loop. Each call starts with empty caches, so the contract holds for each call, not for the loop, and
697 the documentation says to use one `select()` or `filter()` instead. `filter()` with a list shares a
698 `CSSMatch` between the tags under the same top level element, except for a selector that uses `:scope`
699 or `&`, where each tag is the scope and is matched separately, as with `match()`.
701 A report of polynomial time needs a document that breaks the contract, with time measured at increasing
702 sizes, not only a slow example: a large document is slow in linear time too.
704 Memory follows the same contract. The caches that keep matching linear belong to one call of `select()`,
705 `match()`, `filter()` or `closest()`, or to one `iselect()` for as long as it is iterated, and are freed
706 with it, so nothing builds up across calls. Each entry records work that was done, so a cache grows no
707 faster than the time spent matching: at most in proportion to the size of the selector times the size of
708 the document. For example, `:has()`, the descendant combinator and `~` keep an entry for each element and
709 each of these relations in the selector, so a selector with many of them on a large document can use a lot
710 of memory, but it takes as long to match. Limiting the selectors that are accepted, such as with `ignore`
711 or `max_selectors`, limits both.
713 The caches are not bounded, and should not be. Evicting entries brings back the work that they avoid, so a
714 bounded cache, such as a least recently used one, makes matching quadratic again on the large documents the
715 caches are there for, unless the bound is at least the number of entries anyway. It also slows every cache
716 access, and `contains_text()` relies on its entries staying in the cache. A report of excessive memory needs
717 memory that grows faster than the time spent matching.
718 """
720 def __init__(
721 self,
722 selectors: ct.SelectorList,
723 scope: bs4.Tag | None,
724 namespaces: ct.Namespaces | None,
725 flags: int
726 ) -> None:
727 """Initialize."""
729 self.assert_valid_input(scope)
730 self.tag = scope
731 self.selectors = selectors
732 self.namespaces: ct.Namespaces | dict[str, str] = {} if namespaces is None else namespaces
733 self.flags = flags
735 # Caches for this call of `select()`, `iselect()`, `match()` or `filter()`.
736 #
737 # They assume the tree does not change during the call. Changing it during a lazy iteration such as
738 # `iselect()` is only supported with `NOCACHE`, which turns off every one of these caches, so results
739 # then reflect the tree as it is when each element is matched. Changing the tree with caching on can
740 # give stale results, and that is expected: there is no cheap way to detect a change, and clearing
741 # the caches for every element would make many selectors quadratic again.
742 #
743 # So a new cache must be declared here, only be read or written when `enable_cache` is true, and be
744 # cleared in `reset()`. Keys are the `id()` of elements, which stay valid as long as the tree does
745 # not change. The pattern cache in `css_parser` and `util.lower()` do not depend on the tree.
746 # The caches are not bounded: the class documentation explains why, and how much memory they can use.
747 #
748 # The one exception is `lang_match_cache`, which is used even with `NOCACHE`. It holds whether a
749 # language matches a `:lang()`, keyed by the `:lang()` of the compiled selector, which lives as long
750 # as this object, and by the language itself, not by an element. Nothing in it comes from the tree,
751 # so it cannot go stale, and without it a long language tag shared by many elements would make
752 # `:lang()` quadratic.
753 self.enable_cache = not bool(self.flags & util.NOCACHE)
754 self.nth_cache: dict[Hashable, NthState] = {}
755 # The caches of relations are keyed by the relation first, then the element, as a key of both in a tuple
756 # takes about twice the memory, and they can hold an entry for every element and relation of a selector.
757 self.sib_cache: dict[int, dict[int, int]] = {}
758 self.anc_cache: dict[int, dict[int, bool]] = {}
759 self.desc_cache: dict[int, dict[int, bool]] = {}
760 self.dir_cache: dict[int, int] = {}
761 self.lang_cache: dict[int, str] = {}
762 self.edit_cache: dict[int, bool] = {}
763 self.tree_cache: dict[int, bs4.Tag] = {}
764 self.select_cache: dict[int, bs4.Tag | None] = {}
765 self.index_cache: dict[int, dict[int, int]] = {}
766 self.form_cache: dict[int, TreeForms] = {}
767 self.option_cache: dict[int, dict[int, bool]] = {}
768 self.contains_cache: dict[tuple[int, int], tuple[bool, str, str, int]] = {}
769 self.contains_patterns: dict[int, tuple[re.Pattern[str] | None, int]] = {}
770 # Used even with `NOCACHE`, as it does not depend on the tree.
771 self.lang_match_cache: dict[tuple[int, str], bool] = {}
773 # Find the root element for the whole tree
774 doc = scope
775 parent = self.get_parent(doc, no_template=False)
776 while parent:
777 doc = parent
778 parent = self.get_parent(doc, no_template=False)
779 root: bs4.Tag | None = None
780 if not self.is_doc(doc):
781 root = doc
782 else:
783 for child in self.get_tag_children(doc):
784 root = child
785 break
787 self.root = root
788 self.scope = scope if scope is not doc else root
789 self.has_html_namespace = self.has_html_ns(root)
791 # Parsers either record a namespace for every element or for none. The root
792 # alone can't be expected to be HTML as a non-HTML element may have been detached.
793 self.has_namespaces = bool(self.get_uri(root))
795 # A document can be both XML and HTML (XHTML)
796 self.is_xml = self.is_xml_tree(doc)
797 self.is_html = not self.is_xml or self.has_html_namespace
799 def reset(self) -> None: # pragma: no cover
800 """Reset."""
802 self.nth_cache.clear()
803 self.sib_cache.clear()
804 self.anc_cache.clear()
805 self.desc_cache.clear()
806 self.dir_cache.clear()
807 self.lang_cache.clear()
808 self.edit_cache.clear()
809 self.tree_cache.clear()
810 self.select_cache.clear()
811 self.index_cache.clear()
812 self.form_cache.clear()
813 self.option_cache.clear()
814 self.contains_cache.clear()
815 self.contains_patterns.clear()
816 self.lang_match_cache.clear()
818 def supports_namespaces(self) -> bool:
819 """Check if namespaces are supported in the HTML type."""
821 return self.is_xml or self.has_namespaces
823 def get_tag_ns(self, el: bs4.Tag | None) -> str:
824 """Get tag namespace."""
826 namespace = ''
827 if el is None: # pragma: no cover
828 return namespace
830 if self.supports_namespaces():
831 ns = self.get_uri(el)
832 if ns:
833 namespace = ns
834 else:
835 namespace = NS_XHTML
836 return namespace
838 def is_html_tag(self, el: bs4.Tag | None) -> bool:
839 """Check if tag is in HTML namespace."""
841 return self.get_tag_ns(el) == NS_XHTML
843 def get_tag(self, el: bs4.Tag | None) -> str | None:
844 """Get tag."""
846 name = self.get_tag_name(el)
847 return util.lower(name) if name is not None and not self.is_xml else name
849 def get_prefix(self, el: bs4.Tag) -> str | None:
850 """Get prefix."""
852 prefix = self.get_prefix_name(el)
853 return util.lower(prefix) if prefix is not None and not self.is_xml else prefix
855 @staticmethod
856 def find_text_dir(text: str) -> int | None:
857 """Get directionality from the first character of the text with a strong direction."""
859 for c in text:
860 direction = bidi.DIRECTIONS[bisect_right(bidi.STARTS, ord(c)) - 1]
861 if direction != 'N':
862 return ct.SEL_DIR_LTR if direction == 'L' else ct.SEL_DIR_RTL
863 return None
865 def find_bidi(self, el: bs4.Tag) -> int | None:
866 """Get directionality from element text."""
868 stack = [self.get_children(el)]
869 while stack:
870 for node in stack[-1]:
872 # Analyze child text nodes
873 if self.is_tag(node):
875 # Avoid analyzing certain elements specified in the specification. This only applies
876 # to HTML elements: the text of others (SVG, MathML, etc.) is analyzed like any other.
877 if self.is_html_tag(node) and (
878 self.get_tag(node) in AUTO_DIR_IGNORED_ELEMENTS or
879 DIR_MAP.get(util.lower(self.get_attribute_by_name(node, 'dir', '')), None) is not None
880 ):
881 continue # pragma: no cover
883 # Check directionality of this node's text, then resume with the remaining siblings.
884 stack.append(self.get_children(node))
885 break
887 # Skip `doctype` comments, etc.
888 if self.is_special_string(node):
889 continue
891 # Analyze text nodes for directionality.
892 direction = self.find_text_dir(cast('bs4.element.NavigableString', node))
893 if direction is not None:
894 return direction
895 else:
896 # All children have been analyzed and direction could not be determined.
897 stack.pop()
898 return None
900 def extended_language_filter(self, lang_range: str, lang_tag: str) -> bool:
901 """
902 Filter the language tags.
904 `lang_tag` is a well-formed language tag, or an empty string if the language is untagged.
905 """
907 # Only an empty range matches an untagged language, and a range that is not well-formed matches nothing.
908 if not lang_range or not lang_tag:
909 return not lang_range and not lang_tag
910 if RE_LANG_RANGE.fullmatch(lang_range) is None:
911 return False
913 match = True
914 # Wildcards after the first subtag are ignored (RFC 4647 section 3.3.2, step 3.A), as subtags in between are
915 # already skipped implicitly. So `en-*` is the same as `en` and `de-*-DE` the same as `de-DE`.
916 first, *rest = lang_range.lower().split('-')
917 ranges = [first, *(r for r in rest if r != '*')]
918 subtags = lang_tag.lower().split('-')
919 length = len(ranges)
920 rindex = 0
921 sindex = 0
922 r = ranges[rindex]
923 s = subtags[sindex]
925 # Primary tag needs to match
926 if r != '*' and r != s:
927 match = False
929 rindex += 1
930 sindex += 1
932 # Match until we run out of ranges
933 while match and rindex < length:
934 r = ranges[rindex]
935 try:
936 s = subtags[sindex]
937 except IndexError:
938 # Ran out of subtags,
939 # but we still have ranges
940 match = False
941 continue
943 # Matched range
944 if s == r:
945 rindex += 1
947 # Implicit wildcard cannot match
948 # singletons
949 elif len(s) == 1:
950 match = False
951 continue
953 # Implicitly matched, so grab next subtag
954 sindex += 1
956 return match
958 def match_attribute_name(
959 self,
960 el: bs4.Tag,
961 attr: str,
962 prefix: str | None
963 ) -> str | Sequence[str] | None:
964 """Match attribute name and return value if it exists."""
966 value = None
967 if self.supports_namespaces():
968 value = None
969 # If we have not defined namespaces, we can't very well find them, so don't bother trying.
970 if prefix:
971 ns = self.namespaces.get(prefix)
972 if ns is None and prefix != '*':
973 return None
974 else:
975 ns = None
977 for k, v in self.iter_attributes(el):
979 # Get attribute parts
980 namespace, name = self.split_namespace(el, k)
982 # Can't match a prefix attribute as we haven't specified one to match
983 # Try to match it normally as a whole `p:a` as selector may be trying `p\:a`.
984 if ns is None:
985 if (self.is_xml and attr == k) or (not self.is_xml and util.lower(attr) == util.lower(k)):
986 value = v
987 break
988 # Coverage is not finding this even though it is executed.
989 # Adding a print statement before this (and erasing coverage) causes coverage to find the line.
990 # Ignore the false positive message.
991 continue # pragma: no cover
993 # We can't match our desired prefix attribute as the attribute doesn't have a prefix
994 if namespace is None or (ns != namespace and prefix != '*'):
995 continue
997 # The attribute doesn't match.
998 if (util.lower(attr) != util.lower(name)) if not self.is_xml else (attr != name):
999 continue
1001 value = v
1002 break
1003 else:
1004 for k, v in self.iter_attributes(el):
1005 if util.lower(attr) != util.lower(k):
1006 continue
1007 value = v
1008 break
1009 return value
1011 def match_namespace(self, el: bs4.Tag, tag: ct.SelectorTag) -> bool:
1012 """Match the namespace of the element."""
1014 match = True
1015 namespace = self.get_tag_ns(el)
1016 default_namespace = self.namespaces.get('')
1017 tag_ns = '' if tag.prefix is None else self.namespaces.get(tag.prefix)
1018 # We must match the default namespace if one is not provided
1019 if tag.prefix is None and (default_namespace is not None and namespace != default_namespace):
1020 match = False
1021 # If we specified `|tag`, we must not have a namespace.
1022 elif (tag.prefix is not None and tag.prefix == '' and namespace):
1023 match = False
1024 # Verify prefix matches
1025 elif (
1026 tag.prefix and
1027 tag.prefix != '*' and (tag_ns is None or namespace != tag_ns)
1028 ):
1029 match = False
1030 return match
1032 def match_attributes(self, el: bs4.Tag, attributes: tuple[ct.SelectorAttribute, ...]) -> bool:
1033 """Match attributes."""
1035 match = True
1036 if attributes:
1037 for a in attributes:
1038 temp = self.match_attribute_name(el, a.attribute, a.prefix)
1039 # The case insensitive pattern only applies to HTML elements in HTML documents
1040 pattern: re.Pattern[str] | None
1041 if a.xml_type_pattern and (self.is_xml or not self.is_html_tag(el)):
1042 pattern = a.xml_type_pattern
1043 ignore_case = False
1044 else:
1045 pattern = a.pattern
1046 ignore_case = a.ignore_case
1047 if temp is None and a.inverse:
1048 continue
1049 if temp is None:
1050 match = False
1051 break
1052 if pattern is None:
1053 continue
1054 value = temp if isinstance(temp, str) else ' '.join(temp)
1055 # A case insensitive pattern is compiled for the value converted to ASCII lowercase.
1056 if ignore_case:
1057 value = util.ascii_lower(value)
1058 if pattern.search(value) is None:
1059 match = False
1060 break
1061 return match
1063 def match_tagname(self, el: bs4.Tag, tag: ct.SelectorTag) -> bool:
1064 """Match tag name."""
1066 name = tag.name
1067 if name is None or name == '*':
1068 return True
1069 if self.is_xml:
1070 return name == el.name
1071 el_name = el.name
1072 return util.lower(name) == (util.lower(el_name) if el_name is not None else el_name)
1074 def match_tag(self, el: bs4.Tag, tag: ct.SelectorTag | None) -> bool:
1075 """Match the tag."""
1077 match = True
1078 if tag is not None:
1079 # Verify namespace
1080 if not self.match_tagname(el, tag):
1081 match = False
1082 if match and not self.match_namespace(el, tag):
1083 match = False
1084 return match
1086 def within(self, target: bs4.Tag, parent: bs4.Tag | bs4.BeautifulSoup, start: int, end: int | None = None) -> bool:
1087 """
1088 Check if target is within the parent's contents from `start` up to `end`.
1090 Searching the contents for every target is quadratic on parents with many children,
1091 so cache the index of each child the first time a parent is checked.
1092 """
1094 key = id(parent)
1095 if key not in self.index_cache:
1096 self.index_cache[key] = {id(child): i for i, child in enumerate(parent.contents)}
1097 index = self.index_cache[key].get(id(target), -1)
1098 return start <= index < (end if end is not None else len(parent.contents))
1100 def match_general_sibling(self, el: bs4.Tag, relation: ct.SelectorList) -> MatchGenerator:
1101 """Match general sibling combinator."""
1103 found = False
1105 if relation[0] is ct.Null: # pragma: no cover
1106 return found
1108 pkey: int | None = None
1110 # Get the parent and use the ID for the cache key. Siblings do not need a parent element:
1111 # they can be top level elements in the document or the top level contents of a `template`.
1112 # Only an element that has been detached has no parent, and it has no siblings.
1113 parent = self.get_parent(el, no_doc=False, no_template=False)
1114 if parent is None:
1115 return found
1116 pkey = id(parent)
1118 # Check the cache to see if we already know where the first sibling is,
1119 # and if we do, check if we are on the correct side of it.
1120 # If we've previously searched and found no sibling, there is no sibling.
1121 # Lastly, if this is our first time, setup the cache.
1122 reverse = relation[0].rel_type == REL_HAS_SIBLING
1123 start = len(parent) - 1 if reverse else 0
1124 cache = self.sib_cache.get(id(relation))
1125 if cache is None:
1126 cache = self.sib_cache[id(relation)] = {}
1127 if pkey is not None:
1128 if pkey in cache:
1129 index = cache[pkey]
1130 if index >= 0:
1131 a, b = (index + 1, start + 1) if reverse else (start, index)
1132 return not self.within(el, parent, a, b)
1133 else:
1134 return False
1135 cache[pkey] = start
1137 # Start at the furthest endpoint and walk back towards the element looking for siblings.
1138 # The current element counts as a sibling, but will not cause a match.
1139 passed = False
1140 incr = -1 if reverse else 1
1141 for child in self.get_children(parent, start=start, reverse=reverse, template_contents=True):
1142 start += incr
1143 if not isinstance(child, bs4.Tag):
1144 continue
1146 # Flag that we are passing the element.
1147 # Any siblings we find aren't valid for this element.
1148 if child is el:
1149 passed = True
1151 # We found the furthest sibling.
1152 if (yield child, relation):
1153 found = True
1154 break
1156 # Cache the index of the sibling or mark as there being no siblings.
1157 if pkey:
1158 cache[pkey] = start if found else -1
1160 # If we passed the current element and then found a sibling, it doesn't count as a match.
1161 if passed:
1162 found = False
1164 return found
1166 def match_ancestor(self, el: bs4.Tag, relation: ct.SelectorList) -> MatchGenerator:
1167 """
1168 Match descendant combinator.
1170 A selector with several descendant combinators tries every ancestor for each one, which is
1171 a polynomial of the depth with a degree of the number of combinators. Every element visited
1172 on the walk shares the result, so cache whether each one is or has a matching ancestor.
1173 """
1175 found = False
1176 cache = self.anc_cache.get(id(relation))
1177 if cache is None:
1178 cache = self.anc_cache[id(relation)] = {}
1179 visited: list[int] = []
1180 parent: bs4.Tag | None = el
1181 while not found and parent and (parent := self.get_parent(parent)):
1182 key = id(parent)
1183 if key in cache:
1184 found = cache[key]
1185 break
1186 visited.append(key)
1187 found = yield parent, relation
1189 for key in visited:
1190 cache[key] = found
1192 return found
1194 def match_past_relations(self, el: bs4.Tag, relation: ct.SelectorList) -> MatchGenerator:
1195 """Match past relationship."""
1197 found = False
1198 # I don't think this can ever happen, but it makes `mypy` happy
1199 if relation[0] is ct.Null: # pragma: no cover
1200 return found
1202 if relation[0].rel_type == REL_PARENT:
1203 if self.enable_cache:
1204 found = yield from self.match_ancestor(el, relation)
1205 else:
1206 parent: bs4.Tag | None = el
1207 while not found and parent and (parent := self.get_parent(parent)):
1208 found = parent is not None and (yield parent, relation)
1209 elif relation[0].rel_type == REL_CLOSE_PARENT:
1210 parent = self.get_parent(el)
1211 if parent is None:
1212 pass
1213 elif self.enable_cache:
1214 # Siblings share the parent, so cache whether it matches to avoid evaluating it again for every child.
1215 # This is inlined, instead of going through `match_ancestor`, as an extra generator is costly on
1216 # documents where most parents have a single child and the cache rarely gets a hit.
1217 cache = self.anc_cache.get(id(relation))
1218 if cache is None:
1219 cache = self.anc_cache[id(relation)] = {}
1220 key = id(parent)
1221 cached = cache.get(key)
1222 if cached is None:
1223 cached = cache[key] = yield parent, relation
1224 found = cached
1225 else:
1226 found = yield parent, relation
1227 elif relation[0].rel_type == REL_SIBLING:
1228 if self.enable_cache:
1229 found = yield from self.match_general_sibling(el, relation)
1230 else:
1231 sibling: bs4.Tag | None = el
1232 while not found and sibling and (sibling := self.get_previous_tag(sibling)):
1233 found = sibling is not None and (yield sibling, relation)
1234 elif relation[0].rel_type == REL_CLOSE_SIBLING:
1235 sibling = self.get_previous_tag(el)
1236 found = sibling is not None and (yield sibling, relation)
1237 return found
1239 def match_future_child(
1240 self,
1241 parent: bs4.Tag,
1242 relation: ct.SelectorList,
1243 recursive: bool = False
1244 ) -> MatchGenerator:
1245 """Match future child."""
1247 match = False
1248 if recursive:
1249 children: Callable[..., Iterator[bs4.Tag]] = self.get_tag_descendants
1250 else:
1251 children = self.get_tag_children
1252 for child in children(parent):
1253 if (yield child, relation):
1254 match = True
1255 break
1256 return match
1258 def match_descendant(self, el: bs4.Tag, relation: ct.SelectorList) -> MatchGenerator:
1259 """
1260 Match descendant relation of `:has()`.
1262 Every element matched by `:has()` searches all of its descendants, which is quadratic in the depth
1263 of the document. Every element visited on the search shares the result, so cache whether each one
1264 is or has a matching descendant: an element searched without a match is cached along with all of
1265 its descendants, and when there is a match, the element and all of those it is nested in are cached.
1266 """
1268 found = False
1269 cache = self.desc_cache.get(id(relation))
1270 if cache is None:
1271 cache = self.desc_cache[id(relation)] = {}
1272 # Elements whose contents are being searched, outermost first, and elements searched without a match
1273 searching: list[int] = []
1274 searched: list[int] = []
1275 stack = [self.get_tag_children(el)]
1276 while stack and not found:
1277 for child in stack[-1]:
1278 key = id(child)
1279 if key in cache:
1280 if cache[key]:
1281 found = True
1282 break
1283 continue
1284 searching.append(key)
1285 if (yield child, relation):
1286 found = True
1287 else:
1288 stack.append(self.get_tag_children(child))
1289 break
1290 else:
1291 stack.pop()
1292 if searching:
1293 searched.append(searching.pop())
1295 for key in searching:
1296 cache[key] = True
1297 for key in searched:
1298 cache[key] = False
1300 return found
1302 def match_future_relations(self, el: bs4.Tag, relation: ct.SelectorList) -> MatchGenerator:
1303 """Match future relationship."""
1305 found = False
1306 # I don't think this can ever happen, but it makes `mypy` happy
1307 if relation[0] is ct.Null: # pragma: no cover
1308 return found
1310 if relation[0].rel_type == REL_HAS_PARENT:
1311 if self.enable_cache:
1312 found = yield from self.match_descendant(el, relation)
1313 else:
1314 found = yield from self.match_future_child(el, relation, True)
1315 elif relation[0].rel_type == REL_HAS_CLOSE_PARENT:
1316 found = yield from self.match_future_child(el, relation)
1317 elif relation[0].rel_type == REL_HAS_SIBLING:
1318 if self.enable_cache:
1319 found = yield from self.match_general_sibling(el, relation)
1320 else:
1321 sibling: bs4.Tag | None = el
1322 while not found and sibling and (sibling := self.get_next_tag(sibling)):
1323 found = yield sibling, relation
1324 elif relation[0].rel_type == REL_HAS_CLOSE_SIBLING:
1325 sibling = self.get_next_tag(el)
1326 found = sibling is not None and (yield sibling, relation)
1327 return found
1329 def match_relations(self, el: bs4.Tag, relation: ct.SelectorList) -> MatchGenerator:
1330 """Match relationship to other elements."""
1332 sel = relation[0]
1333 if sel is not ct.Null and sel.rel_type is not None and sel.rel_type.startswith(':'):
1334 return self.match_future_relations(el, relation)
1335 return self.match_past_relations(el, relation)
1337 def match_id(self, el: bs4.Tag, ids: tuple[str, ...]) -> bool:
1338 """Match element's ID."""
1340 found = True
1341 for i in ids:
1342 if i != self.get_attribute_by_name(el, 'id', ''):
1343 found = False
1344 break
1345 return found
1347 def match_classes(self, el: bs4.Tag, classes: tuple[str, ...]) -> bool:
1348 """Match element's classes."""
1350 current_classes = self.get_classes(el)
1351 found = True
1352 for c in classes:
1353 if c not in current_classes:
1354 found = False
1355 break
1356 return found
1358 def match_root(self, el: bs4.Tag) -> bool:
1359 """Match element as root."""
1361 is_root = self.is_root(el)
1362 if is_root:
1363 sibling: Any = self.get_previous(el)
1364 while is_root and sibling is not None:
1365 if (
1366 self.is_tag(sibling) or (self.is_content_string(sibling) and RE_NOT_EMPTY.search(sibling)) or
1367 self.is_cdata(sibling)
1368 ):
1369 is_root = False
1370 else:
1371 sibling = self.get_previous(sibling)
1372 if is_root:
1373 sibling = self.get_next(el)
1374 while is_root and sibling is not None:
1375 if (
1376 self.is_tag(sibling) or (self.is_content_string(sibling) and RE_NOT_EMPTY.search(sibling)) or
1377 self.is_cdata(sibling)
1378 ):
1379 is_root = False
1380 else:
1381 sibling = self.get_next(sibling)
1382 return is_root
1384 def match_scope(self, el: bs4.Tag) -> bool:
1385 """Match element as scope."""
1387 return self.scope is el
1389 def match_nth_tag_type(self, el: bs4.Tag, child: bs4.Tag) -> bool:
1390 """Match tag type for `nth` matches."""
1392 return (
1393 (self.get_tag(child) == self.get_tag(el)) and
1394 (self.get_tag_ns(child) == self.get_tag_ns(el))
1395 )
1397 def match_nth_candidate(self, el: bs4.Tag, child: bs4.Tag, n: ct.SelectorNth) -> MatchGenerator:
1398 """Check if a sibling is counted by the `nth` selector (`of-type` or `of S`)."""
1400 if n.of_type and not self.match_nth_tag_type(el, child):
1401 return False
1402 if n.selectors and not (yield child, n.selectors):
1403 return False
1404 return True
1406 def get_nth_index(
1407 self,
1408 el: bs4.Tag,
1409 parent: bs4.Tag | bs4.BeautifulSoup | None,
1410 n: ct.SelectorNth
1411 ) -> Generator[MatchRequest, bool, int]:
1412 """
1413 Get the 1-based index of `el` among the siblings counted by `n`, or 0 if `el` is not counted.
1415 When caching is enabled, each sibling is evaluated against `n` at most once per parent.
1416 The siblings are scanned lazily in document order and the position of every counted sibling
1417 is recorded, so a lookup costs amortized O(1) no matter what order elements are queried in.
1418 This matters as an `nth` selector's `of S` may contain other `nth` selectors, which will then
1419 be queried in whatever order the outer selector walks its siblings.
1420 """
1422 # No parent, just evaluate the element against the selectors
1423 if parent is None:
1424 return 1 if (yield from self.match_nth_candidate(el, el, n)) else 0
1426 # Non-cached handling of parented element
1427 if not self.enable_cache:
1428 index = 0
1429 for child in self.get_children(parent, reverse=n.last, tags=True, template_contents=True):
1430 if (yield from self.match_nth_candidate(el, child, n)):
1431 index += 1
1432 if child is el:
1433 return index
1434 elif child is el:
1435 break
1436 return 0
1438 # Siblings of every type share one state for `of-type`, as a state for each type would scan the siblings
1439 # again for each type, which is quadratic when many siblings have distinct tag names.
1440 key = (id(parent), id(n))
1441 state = self.nth_cache.get(key)
1442 if state is None:
1443 # Next content position to scan, number of counted siblings found, their positions,
1444 # and the number found of each type for `of-type`.
1445 state = self.nth_cache[key] = NthState(0, 0, {}, {} if n.of_type else None)
1446 counts = state.counts
1448 # "Last" selectors need the total count, so scan all siblings, otherwise just scan up to `el`.
1449 contents = parent.contents
1450 if n.last:
1451 end = len(contents)
1452 else:
1453 pkey = id(parent)
1454 if pkey not in self.index_cache:
1455 self.index_cache[pkey] = {id(child): i for i, child in enumerate(contents)}
1456 end = self.index_cache[pkey][id(el)] + 1
1458 while state.pos < end:
1459 node = contents[state.pos]
1460 if self.is_tag(node):
1461 child = cast('bs4.Tag', node)
1462 if counts is not None:
1463 # `of-type`: count the sibling among those of its own type.
1464 tkey = (self.get_tag(child), self.get_tag_ns(child))
1465 count = counts[tkey] = counts.get(tkey, 0) + 1
1466 state.positions[id(child)] = count
1467 elif not n.selectors or (yield child, n.selectors):
1468 state.count += 1
1469 state.positions[id(child)] = state.count
1470 state.pos += 1
1472 index = state.positions.get(id(el), 0)
1473 if index and n.last:
1474 total = state.count if counts is None else counts[(self.get_tag(el), self.get_tag_ns(el))]
1475 index = total - index + 1
1476 return index
1478 def match_nth(self, el: bs4.Tag, nth: tuple[ct.SelectorNth, ...]) -> MatchGenerator:
1479 """Match `nth` elements."""
1481 # The top level contents of a `template` have no parent element, but they do have siblings.
1482 parent = self.get_parent(el, no_doc=False, no_template=False)
1484 for n in nth:
1485 index = yield from self.get_nth_index(el, parent, n)
1486 if not index:
1487 return False
1488 if n.a != 0:
1489 # `index` matches if `index = a * k + b` for an integer `k >= 0`. Integer arithmetic is used as `a`
1490 # and `b` can be of any size, and a float division would overflow or lose precision.
1491 diff = index - n.b
1492 if diff % n.a or diff // n.a < 0:
1493 return False
1494 elif index != n.b:
1495 return False
1496 return True
1498 def match_empty(self, el: bs4.Tag) -> bool:
1499 """Check if element is empty (if requested)."""
1501 is_empty = True
1502 child: Any
1503 for child in self.get_children(el):
1504 if self.is_tag(child):
1505 is_empty = False
1506 break
1507 elif self.is_content_string(child) and RE_NOT_EMPTY.search(child):
1508 is_empty = False
1509 break
1510 return is_empty
1512 def match_subselectors(self, el: bs4.Tag, selectors: tuple[ct.SelectorList, ...]) -> MatchGenerator:
1513 """Match selectors."""
1515 match = True
1516 for sel in selectors:
1517 if not (yield el, sel):
1518 match = False
1519 return match
1521 def contains_text(self, el: bs4.Tag, contain_list: ct.SelectorContains) -> bool:
1522 """
1523 Check if the text of an element, as `get_text()` gets it, contains any of the values of `contain_list`.
1525 Getting the text of every element to search it takes time quadratic in the depth of the document, as an
1526 element's text includes that of all its descendants. Instead, each element is summarized once for the
1527 list, from the summaries of its children, and cached: whether its text contains any of the values, its
1528 length, and its first and last `n - 1` characters, where `n` is the length of the longest value. An
1529 occurrence of a value that crosses the boundary between two children has at most `n - 1` characters on
1530 each side of it, so searching the end of what comes before the boundary joined to the start of what comes
1531 after it finds every one of them.
1533 All the values are searched for at once, with a pattern of all of them, so the summary of an element and
1534 the work to make it don't grow with the number of values, only the searches themselves do, as with the
1535 text of a value.
1537 The first element checked is summarized along with all of its descendants, and the elements below it
1538 that are checked later are found in the cache. Only an element's parent uses its first and last
1539 characters, so once the parent is summarized, they are dropped from the element's summary. Otherwise,
1540 the cache would hold up to `2 * (n - 1)` characters for every element, which adds up for a long value
1541 on a large document. A parent is never summarized again, and checking the element itself only needs
1542 whether its text contains a value.
1543 """
1545 list_key = id(contain_list)
1546 compiled = self.contains_patterns.get(list_key)
1547 if compiled is None:
1548 values = set(contain_list.text)
1549 if '' in values:
1550 # Every text contains an empty value.
1551 compiled = (None, 0)
1552 else:
1553 ordered = sorted(values, key=len, reverse=True)
1554 compiled = (re.compile('|'.join(re.escape(v) for v in ordered)), len(ordered[0]) - 1)
1555 self.contains_patterns[list_key] = compiled
1556 pattern, edge = compiled
1557 if pattern is None:
1558 return True
1559 search = pattern.search
1561 cache = self.contains_cache
1562 stack = [(el, False)]
1563 while stack:
1564 node, children_done = stack.pop()
1565 key = (id(node), list_key)
1566 if key in cache:
1567 continue
1568 # Like `get_text()`, the contents of a `template` are not included.
1569 contents = node.contents if self.has_contents(node, False) else []
1570 if not children_done:
1571 stack.append((node, True))
1572 stack.extend(
1573 (child, False) for child in contents
1574 if isinstance(child, bs4.Tag) and (id(child), list_key) not in cache
1575 )
1576 continue
1578 found = False
1579 head = tail = ''
1580 length = 0
1581 for child in contents:
1582 if isinstance(child, bs4.Tag):
1583 c_found, c_head, c_tail, c_length = cache[(id(child), list_key)]
1584 elif self.is_content_string(child):
1585 string = str(child)
1586 c_found = not found and search(string) is not None
1587 c_head = string[:edge]
1588 c_tail = string[-edge:] if edge else ''
1589 c_length = len(string)
1590 else:
1591 continue
1592 if not found:
1593 found = c_found or (edge > 0 and search(tail + c_head) is not None)
1594 if length < edge:
1595 head = (head + c_head)[:edge]
1596 if edge:
1597 # A child shorter than `edge` is entirely in its head.
1598 tail = (tail + (c_tail if c_length >= edge else c_head))[-edge:]
1599 length += c_length
1600 cache[key] = (found, head, tail, length)
1602 # The ends of the children are no longer needed.
1603 for child in contents:
1604 if isinstance(child, bs4.Tag):
1605 child_key = (id(child), list_key)
1606 c_found, _, _, c_length = cache[child_key]
1607 cache[child_key] = (c_found, '', '', c_length)
1609 return cache[(id(el), list_key)][0]
1611 def match_contains(self, el: bs4.Tag, contains: tuple[ct.SelectorContains, ...]) -> bool:
1612 """Match element if it contains text."""
1614 match = True
1615 content: str | None = None
1616 own_content: Sequence[str] | None = None
1617 for contain_list in contains:
1618 found = False
1619 if not contain_list.own and self.enable_cache:
1620 found = self.contains_text(el, contain_list)
1621 else:
1622 for text in contain_list.text:
1623 if contain_list.own:
1624 if own_content is None:
1625 own_content = self.get_own_text(el)
1626 if any(text in c for c in own_content):
1627 found = True
1628 break
1629 else:
1630 if content is None:
1631 content = self.get_text(el)
1632 if text in content:
1633 found = True
1634 break
1635 if not found:
1636 match = False
1637 return match
1639 def get_tree(self, el: bs4.Tag) -> bs4.Tag:
1640 """Get the top of the tree that an element is in: its document or `template`."""
1642 # Every element visited shares the top of the tree, so cache it to avoid walking the same ancestors again.
1643 visited: list[int] = []
1644 top = el
1645 parent = self.get_parent(top, no_doc=False, no_template=False)
1646 while parent is not None:
1647 key = id(top)
1648 if key in self.tree_cache:
1649 top = self.tree_cache[key]
1650 break
1651 visited.append(key)
1652 top = parent
1653 if self.is_template(top):
1654 break
1655 parent = self.get_parent(top, no_doc=False, no_template=False)
1656 if self.enable_cache:
1657 for key in visited:
1658 self.tree_cache[key] = top
1659 return top
1661 def is_submit_button(self, el: bs4.Tag) -> bool:
1662 """Check if an `input` or `button` is a submit button."""
1664 v = util.lower(cast(str, self.get_attribute_by_name(el, 'type', '')))
1665 if self.get_tag(el) == 'input':
1666 return v in ('submit', 'image')
1668 # A button with a missing or invalid `type` submits, unless it invokes a command or is
1669 # a child of a `select`.
1670 return v == 'submit' or (
1671 v not in ('button', 'reset') and
1672 self.get_attribute_by_name(el, 'command') is None and
1673 self.get_attribute_by_name(el, 'commandfor') is None and
1674 self.get_tag(self.get_parent(el)) != 'select'
1675 )
1677 def get_forms(self, tree: bs4.Tag) -> TreeForms:
1678 """
1679 Get the form information of a tree.
1681 A form owner is the form that the `form` attribute refers to, if there is one, otherwise the nearest
1682 ancestor form. The attribute is only used by elements connected to a document, which the contents of
1683 a `template` are not. A `template` holds its own tree, so it is not entered.
1685 This requires a pass through the whole tree as the `form` attribute can refer to any form, so it is
1686 cached instead of searching the tree again for every element.
1688 A form in a form only exists in XML and in a `template`. Anywhere else, it can only have come from a
1689 parser that doesn't follow the HTML specification. A browser's parser would have ignored the nested
1690 form and taken its end tag for that of the parent, so what it holds belongs to the parent, and
1691 what follows it does not.
1692 """
1694 key = id(tree)
1695 if self.enable_cache:
1696 cached = self.form_cache.get(key)
1697 if cached is not None:
1698 return cached
1700 ids: dict[str, bs4.Tag] = {}
1701 controls: list[tuple[bs4.Tag, bs4.Tag | None]] = []
1702 closed: set[int] = set()
1703 nesting = self.is_xml or self.is_template(tree)
1704 stack: list[tuple[bs4.Tag | None, bs4.Tag | None]] = [
1705 (el, None) for el in self.get_children(tree, reverse=True, tags=True, template_contents=True)
1706 ]
1707 while stack:
1708 el, form = stack.pop()
1710 # The end of a nested form, which ends the form it is in
1711 if el is None:
1712 closed.add(id(form))
1713 continue
1715 if id(form) in closed:
1716 form = None
1717 name = self.get_tag(el) if self.is_html_tag(el) else None
1718 if name == 'form' and form is not None and not nesting:
1719 stack.append((None, form))
1720 else:
1721 el_id = cast(str, self.get_attribute_by_name(el, 'id', ''))
1722 if el_id:
1723 ids.setdefault(el_id, el)
1724 if name == 'form':
1725 form = el
1726 elif name in ('input', 'button'):
1727 controls.append((el, form))
1728 stack.extend((child, form) for child in self.get_tag_children(el, reverse=True))
1730 forms = TreeForms({}, {}, {})
1731 connected = not self.is_template(tree)
1732 for el, form in controls:
1733 form_id = self.get_attribute_by_name(el, 'form')
1734 if connected and form_id is not None:
1735 form = ids.get(cast(str, form_id))
1736 if form is not None and not (self.get_tag(form) == 'form' and self.is_html_tag(form)):
1737 form = None
1738 forms.owners[id(el)] = form
1740 # Controls are in tree order, so the first submit button of a form is its default button,
1741 # and the last radio button with `checked` in a radio button group is the one left checked.
1742 radio_name = cast(str, self.get_attribute_by_name(el, 'name', ''))
1743 if form is not None and self.is_submit_button(el):
1744 forms.defaults.setdefault(id(form), el)
1745 elif (
1746 radio_name and
1747 self.get_attribute_by_name(el, 'checked') is not None and
1748 util.lower(cast(str, self.get_attribute_by_name(el, 'type', ''))) == 'radio'
1749 ):
1750 forms.checked[(id(form), radio_name)] = el
1752 if self.enable_cache:
1753 self.form_cache[key] = forms
1754 return forms
1756 def match_default(self, el: bs4.Tag) -> bool:
1757 """Match the default button of a form, which is the first submit button in the tree that it owns."""
1759 forms = self.get_forms(self.get_tree(el))
1760 form = forms.owners.get(id(el))
1761 return form is not None and forms.defaults.get(id(form)) is el
1763 def get_radio_group(self, el: bs4.Tag, forms: TreeForms) -> tuple[int, str]:
1764 """Get the key of the radio button group of a radio button with a name."""
1766 return id(forms.owners.get(id(el))), cast(str, self.get_attribute_by_name(el, 'name'))
1768 def match_indeterminate(self, el: bs4.Tag) -> bool:
1769 """Match a radio button in a radio button group that has no checked radio buttons."""
1771 forms = self.get_forms(self.get_tree(el))
1772 return self.get_radio_group(el, forms) not in forms.checked
1774 def match_checked_radio(self, el: bs4.Tag) -> bool:
1775 """
1776 Match a radio button with a `checked` attribute if it is still checked.
1778 A radio button that is checked unchecks the others in its group when it is added to a document, so
1779 only the last one is left checked. The contents of a `template` are never added to a document,
1780 so all of them stay checked.
1781 """
1783 if not self.get_attribute_by_name(el, 'name'):
1784 return True
1786 tree = self.get_tree(el)
1787 if self.is_template(tree):
1788 return True
1790 forms = self.get_forms(tree)
1791 return forms.checked.get(self.get_radio_group(el, forms)) is el
1793 def get_options(self, select: bs4.Tag) -> dict[int, bool]:
1794 """
1795 Get the selectedness of each option in the list of options of a `select`.
1797 An option that is not in a `select` with `multiple` is left selected if it is the last one with
1798 a `selected` attribute, and if there are none, the first enabled option is selected when
1799 the `select` shows a single option.
1801 Other than in XML, a nested `option`, `optgroup`, or `select` can only have come from a parser that
1802 doesn't follow the HTML specification. A browser's parser would have ended the first one, so
1803 an `option` or `optgroup` is treated as a sibling, and a `select` ends the list of options.
1804 """
1806 key = id(select)
1807 if self.enable_cache:
1808 cached = self.option_cache.get(key)
1809 if cached is not None:
1810 return cached
1812 options: list[tuple[bs4.Tag, bool]] = []
1813 stack: list[tuple[bs4.Tag, bool | None]] = [
1814 (el, None) for el in self.get_tag_children(select, reverse=True)
1815 ]
1816 while stack:
1817 el, group = stack.pop()
1818 name = self.get_tag(el) if self.is_html_tag(el) else None
1819 if name == 'select' and not self.is_xml:
1820 break
1821 if name == 'option':
1822 options.append((el, bool(group)))
1823 if name in ('select', 'hr', 'datalist') or (
1824 self.is_xml and (name == 'option' or (name == 'optgroup' and group is not None))
1825 ):
1826 continue
1827 if name == 'optgroup':
1828 group = self.get_attribute_by_name(el, 'disabled') is not None
1829 stack.extend((child, group) for child in self.get_tag_children(el, reverse=True))
1831 marked = [el for el, _ in options if self.get_attribute_by_name(el, 'selected') is not None]
1832 if self.get_attribute_by_name(select, 'multiple') is None:
1833 size = RE_SIZE.match(cast(str, self.get_attribute_by_name(select, 'size', '')))
1834 if marked:
1835 marked = marked[-1:]
1836 elif size is None or size.group('value').lstrip('0') in ('', '1'):
1837 marked = [
1838 el for el, disabled in options
1839 if not disabled and self.get_attribute_by_name(el, 'disabled') is None
1840 ][:1]
1842 selected = {id(el) for el in marked}
1843 selectedness = {id(el): id(el) in selected for el, _ in options}
1844 if self.enable_cache:
1845 self.option_cache[key] = selectedness
1846 return selectedness
1848 def match_checked_option(self, el: bs4.Tag) -> bool:
1849 """Match a selected option. Without a `select`, an option is only selected by its `selected` attribute."""
1851 # Every element visited shares the `select`, so cache it to avoid walking the same ancestors again.
1852 visited: list[int] = []
1853 node = el
1854 while True:
1855 key = id(node)
1856 if key in self.select_cache:
1857 parent = self.select_cache[key]
1858 break
1859 visited.append(key)
1860 parent = self.get_parent(node)
1861 if parent is None or (self.get_tag(parent) == 'select' and self.is_html_tag(parent)):
1862 break
1863 node = parent
1864 if self.enable_cache:
1865 for key in visited:
1866 self.select_cache[key] = parent
1868 selected = self.get_options(parent).get(id(el)) if parent is not None else None
1869 return self.get_attribute_by_name(el, 'selected') is not None if selected is None else selected
1871 def match_lang(self, el: bs4.Tag, langs: tuple[ct.SelectorLang, ...]) -> bool:
1872 """Match languages."""
1874 # Every element visited while resolving shares the language,
1875 # so cache it to avoid walking the same ancestors again for each element.
1876 visited: list[int] = []
1877 found_lang = self.resolve_lang(el, visited)
1878 if self.enable_cache:
1879 for key in visited:
1880 self.lang_cache[key] = found_lang
1882 # The result only depends on the language, which elements usually inherit, so match each distinct
1883 # language once per `:lang()`. Checking a long language tag for every element would take time
1884 # quadratic in the size of the document. This does not depend on the tree, so unlike the other
1885 # caches it is also used with `NOCACHE`.
1886 match_key = (id(langs), found_lang)
1887 if match_key in self.lang_match_cache:
1888 return self.lang_match_cache[match_key]
1890 # A language tag that is not well-formed matches nothing, not even `:lang('')` or `:lang('*')`.
1891 if found_lang and RE_LANG_TAG.fullmatch(found_lang) is None:
1892 self.lang_match_cache[match_key] = False
1893 return False
1895 # Each `:lang()` must match, and it matches if any of its values do, so stop at the first value that
1896 # matches, and at the first `:lang()` that doesn't. A list can have any number of values.
1897 match = False
1898 for patterns in langs:
1899 match = False
1900 for pattern in patterns:
1901 if self.extended_language_filter(pattern, found_lang):
1902 match = True
1903 break
1904 if not match:
1905 break
1907 self.lang_match_cache[match_key] = match
1908 return match
1910 def resolve_lang(self, el: bs4.Tag, visited: list[int]) -> str:
1911 """Resolve the language of an element, which is an empty string if it is unknown."""
1913 has_ns = self.supports_namespaces()
1914 root = self.root
1915 has_html_namespace = self.has_html_namespace
1917 # Walk parents looking for `lang` (HTML) or `xml:lang` XML property.
1918 parent: bs4.Tag | None = el
1919 found_lang = None
1920 last = None
1921 while found_lang is None:
1922 key = id(parent)
1923 if key in self.lang_cache:
1924 return self.lang_cache[key]
1925 visited.append(key)
1926 has_html_ns = self.has_html_ns(parent)
1927 # SVG elements also use a `lang` attribute in no namespace, but `xml:lang` takes precedence.
1928 has_svg_ns = has_ns and getattr(parent, 'namespace', None) == NS_SVG
1929 svg_lang = None
1930 for k, v in self.iter_attributes(parent):
1931 attr_ns, attr = self.split_namespace(parent, k)
1932 if (
1933 ((not has_ns or has_html_ns) and (util.lower(k) if not self.is_xml else k) == 'lang') or
1934 (
1935 has_ns and not has_html_ns and attr_ns == NS_XML and
1936 (util.lower(attr) if not self.is_xml and attr is not None else attr) == 'lang'
1937 )
1938 ):
1939 found_lang = v
1940 break
1941 if has_svg_ns and attr_ns is None and (util.lower(k) if not self.is_xml else k) == 'lang':
1942 svg_lang = v
1943 if found_lang is None:
1944 found_lang = svg_lang
1945 last = parent
1946 parent = self.get_parent(parent)
1948 if parent is None:
1949 root = last
1950 has_html_namespace = self.has_html_ns(root)
1951 parent = last
1952 break
1954 # If we couldn't find a language, and the document is HTML, look to meta to determine language.
1955 # This needs no cache of its own: the root is one of the elements visited, so `match_lang()` caches
1956 # the result for it in `lang_cache`, and later walks stop there before getting here again.
1957 if found_lang is None and (not self.is_xml or (has_html_namespace and root and root.name == 'html')):
1958 # Find head
1959 found = False
1960 for tag in ('html', 'head'):
1961 found = False
1962 for child in self.get_tag_children(parent):
1963 if self.get_tag(child) == tag and self.is_html_tag(child):
1964 found = True
1965 parent = child
1966 break
1967 if found: # pragma: no cover
1968 break
1970 # Search meta tags
1971 if found and parent is not None:
1972 for child2 in parent:
1973 if isinstance(child2, bs4.Tag) and self.get_tag(child2) == 'meta' and self.is_html_tag(parent):
1974 c_lang = False
1975 content = None
1976 for k, v in self.iter_attributes(child2):
1977 if util.lower(k) == 'http-equiv' and util.lower(v) == 'content-language':
1978 c_lang = True
1979 if util.lower(k) == 'content':
1980 content = v
1981 if c_lang and content:
1982 found_lang = content
1983 break
1984 if found_lang is not None:
1985 break
1987 # Without any language information, the language is unknown, which is an empty language tag.
1988 return '' if found_lang is None else cast(str, found_lang)
1990 def match_dir(self, el: bs4.Tag, directionality: int) -> bool:
1991 """Check directionality."""
1993 # Direction is only supported in HTML documents.
1994 if not self.is_html:
1995 return False
1997 # If we have to match both left and right, we can't match either.
1998 if directionality & ct.SEL_DIR_LTR and directionality & ct.SEL_DIR_RTL:
1999 return False
2001 # Every element visited while resolving shares the resolved direction,
2002 # so cache it to avoid walking the same ancestors again for each element.
2003 visited: list[int] = []
2004 direction = self.resolve_dir(el, visited)
2005 if self.enable_cache:
2006 for key in visited:
2007 self.dir_cache[key] = direction
2008 return direction == directionality
2010 def resolve_dir(self, el: bs4.Tag, visited: list[int]) -> int:
2011 """Resolve the direction of an element."""
2013 while True:
2014 key = id(el)
2015 if key in self.dir_cache:
2016 return self.dir_cache[key]
2017 visited.append(key)
2019 # `dir` is only defined for HTML elements, so other elements (SVG, MathML, etc.)
2020 # always inherit the direction of their parent.
2021 if self.is_html_tag(el):
2023 # Element has defined direction of left to right or right to left
2024 direction = DIR_MAP.get(util.lower(self.get_attribute_by_name(el, 'dir', '')), None)
2025 if direction not in (None, 0):
2026 return direction
2028 # If `input[type=telephone]` and no direction is assigned, assume left to right.
2029 name = self.get_tag(el)
2030 is_input = name == 'input'
2031 is_textarea = name == 'textarea'
2032 is_bdi = name == 'bdi'
2033 itype = util.lower(self.get_attribute_by_name(el, 'type', '')) if is_input else ''
2034 if is_input and itype == 'tel' and direction is None:
2035 return ct.SEL_DIR_LTR
2037 # Auto handling for inputs whose value is used
2038 if ((is_input and itype not in NON_AUTO_DIR_INPUT_TYPES) or is_textarea) and direction == 0:
2039 if is_textarea:
2040 value = ''.join(
2041 node for node in self.get_contents(el) # type: ignore[misc]
2042 if self.is_content_string(node)
2043 )
2044 else:
2045 value = cast(str, self.get_attribute_by_name(el, 'value', ''))
2046 direction = self.find_text_dir(value)
2047 # No strong directional characters (or no value), assume left to right
2048 return direction if direction is not None else ct.SEL_DIR_LTR
2050 # Auto handling for `bdi` and other non text inputs.
2051 if (is_bdi and direction is None) or direction == 0:
2052 direction = self.find_bidi(el)
2053 if direction is not None:
2054 return direction
2055 # Auto directionality could not be determined, assume left to right
2056 return ct.SEL_DIR_LTR
2058 # Match parents direction. There may be no parent element, and not just for the root:
2059 # a fragment can have many top level elements, and a `template` has its own contents.
2060 # Without one, assume left to right.
2061 parent = self.get_parent(el)
2062 if parent is None:
2063 return ct.SEL_DIR_LTR
2064 el = parent
2066 def match_range(self, el: bs4.Tag, condition: int) -> bool:
2067 """
2068 Match `:in-range` or `:out-of-range`.
2070 Policy: follow the HTML spec, except where all browsers agree on something else, in which case
2071 follow the browsers and document the difference here or in `Inputs.parse_value()`. Before
2072 changing this behavior, check it against the spec and against Chrome, Firefox and Safari. A
2073 report that cites only the spec, or only one browser, is not enough. Where browsers disagree
2074 with each other, follow the spec. Known cases, all deliberate:
2076 - A `range` input whose maximum is less than its minimum: Chrome and Safari match `:in-range`,
2077 Firefox and the spec `:out-of-range` (see below).
2078 - Firefox and Safari do not support `month` or `week` inputs and treat them as text, so Chrome
2079 is the only browser to compare them with.
2080 - Safari accepts a `number` bound with a trailing `.` (`min="20."`), and Firefox accepts such
2081 a value. Neither is a valid floating-point number, and the other browsers reject them.
2083 https://html.spec.whatwg.org/multipage/semantics-other.html#selector-in-range
2085 - `:out-of-range` matches an input that is a candidate for constraint validation, has range
2086 limitations, and is suffering from an underflow or an overflow. `:in-range` matches one that
2087 is a candidate and has range limitations but suffers from neither.
2088 - Being a candidate for constraint validation is checked by `CSS_IN_RANGE` and
2089 `CSS_OUT_OF_RANGE`, which exclude inputs that are disabled, `readonly` or in a `datalist`.
2090 - An input has range limitations if it has a minimum or a maximum. Only `range` has defaults:
2091 0 and 100. For the other types, a `min` or `max` that does not parse is ignored, and an input
2092 with neither matches neither pseudo-class.
2093 - An input suffers from an underflow when its value is below its minimum, and from an overflow
2094 when it is above its maximum. An empty or invalid value is sanitized to the empty string,
2095 which suffers from neither, so it is in range.
2096 - `time` has a periodic domain. When its maximum is less than its minimum, it has a reversed
2097 range, such as 22:00 to 02:00 across midnight, and is out of range only when its value is
2098 both below the minimum and above the maximum.
2099 - The other types do not have a periodic domain. When the maximum is less than the minimum,
2100 any value is out of range, but an empty value is still in range.
2101 - A `range` input's value is clamped to its minimum and maximum, and an invalid or missing
2102 value becomes a default within them, so it is in range unless its maximum is less than its
2103 minimum. In that case, the value is raised to the minimum but is not lowered to the maximum,
2104 so it is always out of range. Chrome and Safari match it as in range instead, which is a
2105 browser bug; Firefox follows the spec, and so do we.
2106 """
2108 out_of_range = False
2110 itype = util.lower(cast(str, self.get_attribute_by_name(el, 'type', '')))
2112 # A `range` input always has a minimum and maximum, 0 and 100 by default, and its value
2113 # is clamped to them, so it is out of range only when its maximum is less than its minimum.
2114 if itype == 'range':
2115 mn = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'min', None)))
2116 mx = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'max', None)))
2117 out_of_range = (mx or (100.0,)) < (mn or (0.0,))
2118 return not out_of_range if condition & ct.SEL_IN_RANGE else out_of_range
2120 mn = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'min', None)))
2121 mx = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'max', None)))
2123 # There is no valid min or max, so we cannot evaluate a range
2124 if mn is None and mx is None:
2125 return False
2127 value = Inputs.parse_value(itype, cast(str, self.get_attribute_by_name(el, 'value', None)))
2128 if value is not None:
2129 if itype in ("date", "datetime-local", "month", "week", "number"):
2130 if mn is not None and value < mn:
2131 out_of_range = True
2132 if not out_of_range and mx is not None and value > mx:
2133 out_of_range = True
2134 elif itype == "time":
2135 if mn is not None and mx is not None and mn > mx:
2136 # Time is periodic, so this is a reversed/discontinuous range
2137 if value < mn and value > mx:
2138 out_of_range = True
2139 else:
2140 if mn is not None and value < mn:
2141 out_of_range = True
2142 if not out_of_range and mx is not None and value > mx:
2143 out_of_range = True
2145 return not out_of_range if condition & ct.SEL_IN_RANGE else out_of_range
2147 def match_defined(self, el: bs4.Tag) -> bool:
2148 """
2149 Match defined.
2151 `:defined` is related to custom elements in a browser.
2153 - If the document is XML (not XHTML), no tags will match.
2154 - Tags that are not custom (don't have a hyphen) are marked defined.
2155 - If the tag has a prefix (without or without a namespace), it will not match.
2156 - HTML elements with an `is` attribute (customized built-in elements) are created as undefined,
2157 like custom tags, so they don't match.
2159 This is of course requires the parser to provide us with the proper prefix and namespace info,
2160 if it doesn't, there is nothing we can do.
2161 """
2163 name = self.get_tag(el)
2164 return (
2165 self.is_html and name is not None and (
2166 (name.find('-') == -1 and not self.is_customized_builtin(el)) or
2167 name.find(':') != -1 or
2168 self.get_prefix(el) is not None
2169 )
2170 )
2172 def is_customized_builtin(self, el: bs4.Tag) -> bool:
2173 """Check if an HTML element has an `is` attribute, which makes it a customized built-in element."""
2175 return self.is_html_tag(el) and self.get_attribute_by_name(el, 'is') is not None
2177 def match_placeholder_shown(self, el: bs4.Tag) -> bool:
2178 """
2179 Match placeholder shown according to HTML spec.
2181 - text area should be checked if they have content. A single newline does not count as content.
2182 - An input's value is sanitized first, and the placeholder is shown when the result is
2183 empty. Text-like inputs drop line breaks, `url` and `email` inputs also drop leading and
2184 trailing whitespace, and a `number` input empties a value that is not a valid
2185 floating-point number, so `value="abc"` still shows the placeholder.
2187 https://html.spec.whatwg.org/multipage/input.html#value-sanitization-algorithm
2189 As in `match_range()`, we follow the spec, except where all browsers agree on something
2190 else. Known cases, all deliberate:
2192 - A `number` value that overflows a double, such as `1e9999`, is emptied, as in Chrome,
2193 Firefox and Safari, although the spec's sanitization keeps it as a valid floating-point
2194 number.
2195 - Firefox keeps `value="1."` for a `number` input, so it hides the placeholder. It is not a
2196 valid floating-point number: Chrome, Safari and the spec empty it, and so do we.
2197 """
2199 name = self.get_tag(el)
2200 if name == 'input':
2201 itype = util.lower(cast(str, self.get_attribute_by_name(el, 'type', '')))
2202 value = cast(str, self.get_attribute_by_name(el, 'value', ''))
2203 value = value.replace('\r', '').replace('\n', '')
2204 if itype in ('url', 'email'):
2205 value = value.strip(' \t\f')
2206 elif itype == 'number' and Inputs.parse_value(itype, value) is None:
2207 value = ''
2208 return value == ''
2210 # This is checked for every element before the rest of the pattern, so only get the text of a `textarea`.
2211 return name == 'textarea' and self.get_text(el) in ('', '\n')
2213 def match_editable(self, el: bs4.Tag) -> bool:
2214 """
2215 Match editing hosts and the elements that are editable inside them.
2217 The nearest `contenteditable` attribute with a valid state decides: an empty value, `true` and
2218 `plaintext-only` make the element editable, and `false` does not. Any other value inherits
2219 the state of the parent. The attribute only applies to HTML elements, others (SVG, MathML,
2220 etc.) always inherit the state of their parent.
2221 """
2223 # Every element visited shares the state, so cache it to avoid walking the same ancestors again.
2224 visited: list[int] = []
2225 editable = False
2226 node = el # type: bs4.Tag | None
2227 while node is not None:
2228 key = id(node)
2229 if key in self.edit_cache:
2230 editable = self.edit_cache[key]
2231 break
2232 visited.append(key)
2233 state = self.get_attribute_by_name(node, 'contenteditable') if self.is_html_tag(node) else None
2234 if isinstance(state, str):
2235 state = util.lower(state)
2236 if state in ('', 'true', 'plaintext-only'):
2237 editable = True
2238 break
2239 if state == 'false':
2240 break
2241 node = self.get_parent(node)
2242 if self.enable_cache:
2243 for key in visited:
2244 self.edit_cache[key] = editable
2245 return editable
2247 def match_selectors(self, el: bs4.Tag, selectors: ct.SelectorList) -> bool:
2248 """
2249 Check if element matches one of the selectors.
2251 Since some selectors can have complex relationships, they may need to recursively
2252 check if another relative element matches specific selectors. To avoid recursion,
2253 generators are yielded instead whenever it needs to check if a relative element
2254 satisfies specific selectors. These can be compared and the result sent back.
2255 We can check the end result of the generator once it is satisfied.
2256 """
2258 # Most matches never need a nested match, so avoid setting up the stack unless needed.
2259 # `frame` yields a `bool` when it is done.
2260 frame = self._match_selectors(el, selectors)
2261 item = next(frame)
2262 if item.__class__ is bool:
2263 return item
2265 # We need to setup a stack as a selector has sent back a match request.
2266 stack = [frame, self._match_selectors(*cast('MatchRequest', item))]
2267 result: bool | None = None
2268 while True:
2269 item = stack[-1].send(result) # type: ignore[arg-type]
2270 if item.__class__ is bool:
2271 stack.pop()
2272 if not stack:
2273 return item
2274 result = item
2275 else:
2276 stack.append(self._match_selectors(*cast('MatchRequest', item)))
2277 result = None
2279 def _match_selectors(self, el: bs4.Tag, selectors: ct.SelectorList) -> Generator[MatchRequest | bool, bool, None]:
2280 """
2281 Check if element matches one of the selectors, yielding requests to match nested selectors.
2283 Yields `MatchRequests` or affirmation as to whether a selector was matched. The match request
2284 requires a boolean to be sent back to communicate whether the match was successful.
2285 """
2287 match = False
2288 is_not = selectors.is_not
2289 is_html = selectors.is_html
2291 # Internal selector lists that use the HTML flag, will automatically get the `html` namespace.
2292 if is_html:
2293 namespaces = self.namespaces
2294 self.namespaces = {'html': NS_XHTML}
2296 if not is_html or self.is_html:
2297 for selector in selectors:
2298 match = is_not
2299 # We have a un-matchable situation (like `:focus` as you can focus an element in this environment)
2300 if selector is ct.Null:
2301 continue
2302 # Verify tag matches
2303 if not self.match_tag(el, selector.tag):
2304 continue
2305 # Verify tag is defined
2306 if selector.flags & ct.SEL_DEFINED and not self.match_defined(el):
2307 continue
2308 # Verify element is root
2309 if selector.flags & ct.SEL_ROOT and not self.match_root(el):
2310 continue
2311 # Verify element is scope
2312 if selector.flags & ct.SEL_SCOPE and not self.match_scope(el):
2313 continue
2314 # Verify element has placeholder shown
2315 if selector.flags & ct.SEL_PLACEHOLDER_SHOWN and not self.match_placeholder_shown(el):
2316 continue
2317 # Verify element is an editing host or editable
2318 if selector.flags & ct.SEL_EDITABLE and not self.match_editable(el):
2319 continue
2320 # Verify `nth` matches
2321 if selector.nth and not (yield from self.match_nth(el, selector.nth)):
2322 continue
2323 if selector.flags & ct.SEL_EMPTY and not self.match_empty(el):
2324 continue
2325 # Verify id matches
2326 if selector.ids and not self.match_id(el, selector.ids):
2327 continue
2328 # Verify classes match
2329 if selector.classes and not self.match_classes(el, selector.classes):
2330 continue
2331 # Verify attribute(s) match
2332 if not self.match_attributes(el, selector.attributes):
2333 continue
2334 # Verify ranges
2335 if selector.flags & RANGES and not self.match_range(el, selector.flags & RANGES):
2336 continue
2337 # Verify language patterns
2338 if selector.lang and not self.match_lang(el, selector.lang):
2339 continue
2340 # Verify pseudo selector patterns
2341 if selector.selectors and not (yield from self.match_subselectors(el, selector.selectors)):
2342 continue
2343 # Verify relationship selectors
2344 if selector.relation and not (yield from self.match_relations(el, selector.relation)):
2345 continue
2346 # Validate that the current default selector match corresponds to the first submit button in the form
2347 if selector.flags & ct.SEL_DEFAULT and not self.match_default(el):
2348 continue
2349 # Validate that the unset radio button is among radio buttons with the same name in a form that are
2350 # also not set.
2351 if selector.flags & ct.SEL_INDETERMINATE and not self.match_indeterminate(el):
2352 continue
2353 # Validate that the radio button is left checked in its group or that the option is selected.
2354 if selector.flags & ct.SEL_CHECKED and not (
2355 self.match_checked_option(el) if self.get_tag(el) == 'option' else self.match_checked_radio(el)
2356 ):
2357 continue
2358 # Validate element directionality
2359 if selector.flags & DIR_FLAGS and not self.match_dir(el, selector.flags & DIR_FLAGS):
2360 continue
2361 # Validate that the tag contains the specified text.
2362 if selector.contains and not self.match_contains(el, selector.contains):
2363 continue
2364 match = not is_not
2365 break
2367 # Restore actual namespaces being used for external selector lists
2368 if is_html:
2369 self.namespaces = namespaces
2371 yield match
2373 def select(self, limit: int = 0) -> Iterator[bs4.Tag]:
2374 """Match all tags under the targeted tag."""
2376 lim = None if limit < 1 else limit
2378 # Selecting from a `template` is how its contents are reached, but only for that `template`.
2379 for child in self.get_tag_descendants(self.tag, template_contents=True):
2380 if self.match(child):
2381 yield child
2382 if lim is not None:
2383 lim -= 1
2384 if lim < 1:
2385 break
2387 def closest(self) -> bs4.Tag | None:
2388 """Match closest ancestor."""
2390 current: bs4.Tag | None = self.tag
2391 closest = None
2392 while closest is None and current is not None:
2393 if self.match(current):
2394 closest = current
2395 else:
2396 current = self.get_parent(current)
2397 return closest
2399 def filter(self) -> list[bs4.Tag]: # noqa A001
2400 """Filter tag's children."""
2402 return [
2403 tag for tag in self.get_contents(self.tag, template_contents=True)
2404 if isinstance(tag, bs4.Tag) and self.match(tag)
2405 ]
2407 def match(self, el: bs4.Tag) -> bool:
2408 """Match."""
2410 return not self.is_doc(el) and self.is_tag(el) and self.match_selectors(el, self.selectors)
2413class SoupSieve(ct.Immutable):
2414 """Compiled Soup Sieve selector matching object."""
2416 pattern: str
2417 selectors: ct.SelectorList
2418 namespaces: ct.Namespaces | None
2419 custom: dict[str, str]
2420 flags: int
2422 __slots__ = ("pattern", "selectors", "namespaces", "custom", "flags", "_hash")
2424 def __init__(
2425 self,
2426 pattern: str,
2427 selectors: ct.SelectorList,
2428 namespaces: ct.Namespaces | None,
2429 custom: ct.CustomSelectors | None,
2430 flags: int
2431 ):
2432 """Initialize."""
2434 super().__init__(
2435 pattern=pattern,
2436 selectors=selectors,
2437 namespaces=namespaces,
2438 custom=custom,
2439 flags=flags
2440 )
2442 def match(self, tag: bs4.Tag) -> bool:
2443 """Match."""
2445 return CSSMatch(self.selectors, tag, self.namespaces, self.flags).match(tag)
2447 def closest(self, tag: bs4.Tag) -> bs4.Tag | None:
2448 """Match closest ancestor."""
2450 return CSSMatch(self.selectors, tag, self.namespaces, self.flags).closest()
2452 def filter(self, iterable: Iterable[bs4.Tag]) -> list[bs4.Tag]: # noqa A001
2453 """
2454 Filter.
2456 Given a tag, its children are filtered with one `CSSMatch`, so its caches are shared by all of them.
2458 Any other iterable can hold tags from different documents, or detached tags. A `CSSMatch` takes what
2459 it knows about a document from the tree the tag it is created with is in, so the tags are grouped by
2460 their document, or by the top level element of a detached tree, and each group shares a `CSSMatch` and
2461 its caches, created with the document as `select()` does. Matching each tag with a new `CSSMatch`
2462 would search the same parts of a document again for every tag, which is quadratic for a selector like
2463 `:has()` or `:-soup-contains()` on the elements of a nested document. The top level elements of a
2464 document are siblings, so they must share one too, or sibling selectors like `:nth-child()` would
2465 count all the top level elements again for every tag, which is quadratic in time and memory on a
2466 fragment with many top level elements.
2468 The one thing a `CSSMatch` knows about the tag it is created with is that it is the scope, which
2469 `:scope` and `&` match, and caches can depend on it. So a selector that uses them still matches
2470 each tag with a new `CSSMatch`, with the tag as the scope, as `match()` does.
2471 """
2473 if isinstance(iterable, bs4.Tag):
2474 return CSSMatch(self.selectors, iterable, self.namespaces, self.flags).filter()
2476 if uses_scope(self.selectors):
2477 return [node for node in iterable if not CSSMatch.is_navigable_string(node) and self.match(node)]
2479 matchers: dict[int, CSSMatch] = {}
2480 tops: dict[int, bs4.Tag] = {}
2481 matched = []
2482 for node in iterable:
2483 if CSSMatch.is_navigable_string(node):
2484 continue
2485 CSSMatch.assert_valid_input(node)
2486 if CSSMatch.is_doc(node):
2487 continue
2489 # Find the top level element above the tag, sharing the walk with the tags it passes through so
2490 # that a nested document is walked once.
2491 visited = []
2492 top = node
2493 while id(top) not in tops:
2494 visited.append(id(top))
2495 parent = top.parent
2496 if parent is None or CSSMatch.is_doc(parent):
2497 break
2498 top = parent
2499 else:
2500 top = tops[id(top)]
2501 for key in visited:
2502 tops[key] = top
2504 # Top level elements of the same document are siblings, so they share one `CSSMatch`, created with the
2505 # document as `select()` does, or a detached tree has one of its own.
2506 group = top.parent if top.parent is not None else top
2507 matcher = matchers.get(id(group))
2508 if matcher is None:
2509 matcher = matchers[id(group)] = CSSMatch(self.selectors, group, self.namespaces, self.flags)
2510 if matcher.match(node):
2511 matched.append(node)
2512 return matched
2514 def select_one(self, tag: bs4.Tag) -> bs4.Tag | None:
2515 """Select a single tag."""
2517 tags = self.select(tag, limit=1)
2518 return tags[0] if tags else None
2520 def select(self, tag: bs4.Tag, limit: int = 0) -> list[bs4.Tag]:
2521 """Select the specified tags."""
2523 return list(self.iselect(tag, limit))
2525 def iselect(self, tag: bs4.Tag, limit: int = 0) -> Iterator[bs4.Tag]:
2526 """Iterate the specified tags."""
2528 yield from CSSMatch(self.selectors, tag, self.namespaces, self.flags).select(limit)
2530 def __repr__(self) -> str: # pragma: no cover
2531 """Representation."""
2533 return (
2534 f"SoupSieve(pattern={self.pattern!r}, namespaces={self.namespaces!r}, "
2535 f"custom={self.custom!r}, flags={self.flags!r})"
2536 )
2538 __str__ = __repr__
2541ct.pickle_register(SoupSieve)