forked from jarun/googler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
googler
executable file
·3858 lines (3275 loc) · 133 KB
/
googler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#
# Copyright © 2008 Henri Hakkinen
# Copyright © 2015-2021 Arun Prakash Jana <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import argparse
import atexit
import base64
import collections
import codecs
import functools
import gzip
import html.entities
import html.parser
import http.client
from http.client import HTTPSConnection
import locale
import logging
import os
import platform
import shutil
import signal
import socket
import ssl
import subprocess
from subprocess import Popen, PIPE, DEVNULL
import sys
import textwrap
import unicodedata
import urllib.parse
import uuid
import webbrowser
# Python optional dependency compatibility layer
try:
import readline
except ImportError:
pass
try:
import setproctitle
setproctitle.setproctitle('googler')
except (ImportError, Exception):
pass
from typing import (
Any,
Dict,
Generator,
Iterable,
Iterator,
List,
Match,
Optional,
Sequence,
Tuple,
Union,
cast,
)
# Basic setup
logging.basicConfig(format='[%(levelname)s] %(message)s')
logger = logging.getLogger()
def sigint_handler(signum, frame):
print('\nInterrupted.', file=sys.stderr)
sys.exit(1)
try:
signal.signal(signal.SIGINT, sigint_handler)
except ValueError:
# signal only works in main thread
pass
# Constants
_VERSION_ = '4.3.2'
_EPOCH_ = '20210115'
COLORMAP = {k: '\x1b[%sm' % v for k, v in {
'a': '30', 'b': '31', 'c': '32', 'd': '33',
'e': '34', 'f': '35', 'g': '36', 'h': '37',
'i': '90', 'j': '91', 'k': '92', 'l': '93',
'm': '94', 'n': '95', 'o': '96', 'p': '97',
'A': '30;1', 'B': '31;1', 'C': '32;1', 'D': '33;1',
'E': '34;1', 'F': '35;1', 'G': '36;1', 'H': '37;1',
'I': '90;1', 'J': '91;1', 'K': '92;1', 'L': '93;1',
'M': '94;1', 'N': '95;1', 'O': '96;1', 'P': '97;1',
'x': '0', 'X': '1', 'y': '7', 'Y': '7;1',
}.items()}
USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
text_browsers = ['elinks', 'links', 'lynx', 'w3m', 'www-browser']
# Self-upgrade parameters
#
# Downstream packagers are recommended to turn off the entire self-upgrade
# mechanism through
#
# make disable-self-upgrade
#
# before running `make install'.
ENABLE_SELF_UPGRADE_MECHANISM = True
API_REPO_BASE = 'https://api.github.com/repos/jarun/googler'
RAW_DOWNLOAD_REPO_BASE = 'https://raw.githubusercontent.com/jarun/googler'
debugger = False
# Monkeypatch textwrap for CJK wide characters.
def monkeypatch_textwrap_for_cjk():
try:
if textwrap.wrap.patched:
return
except AttributeError:
pass
psl_textwrap_wrap = textwrap.wrap
def textwrap_wrap(text, width=70, **kwargs):
if width <= 2:
width = 2
# We first add a U+0000 after each East Asian Fullwidth or East
# Asian Wide character, then fill to width - 1 (so that if a NUL
# character ends up on a new line, we still have one last column
# to spare for the preceding wide character). Finally we strip
# all the NUL characters.
#
# East Asian Width: https://www.unicode.org/reports/tr11/
return [
line.replace('\0', '')
for line in psl_textwrap_wrap(
''.join(
ch + '\0' if unicodedata.east_asian_width(ch) in ('F', 'W') else ch
for ch in unicodedata.normalize('NFC', text)
),
width=width - 1,
**kwargs
)
]
def textwrap_fill(text, width=70, **kwargs):
return '\n'.join(textwrap_wrap(text, width=width, **kwargs))
textwrap.wrap = textwrap_wrap
textwrap.fill = textwrap_fill
textwrap.wrap.patched = True
textwrap.fill.patched = True
monkeypatch_textwrap_for_cjk()
CoordinateType = Tuple[int, int]
class TrackedTextwrap:
"""
Implements a text wrapper that tracks the position of each source
character, and can correctly insert zero-width sequences at given
offsets of the source text.
Wrapping result should be the same as that from PSL textwrap.wrap
with default settings except expand_tabs=False.
"""
def __init__(self, text: str, width: int):
self._original = text
# Do the job of replace_whitespace first so that we can easily
# match text to wrapped lines later. Note that this operation
# does not change text length or offsets.
whitespace = "\t\n\v\f\r "
whitespace_trans = str.maketrans(whitespace, " " * len(whitespace))
text = text.translate(whitespace_trans)
self._lines = textwrap.wrap(
text, width, expand_tabs=False, replace_whitespace=False
)
# self._coords track the (row, column) coordinate of each source
# character in the result text. It is indexed by offset in
# source text.
self._coords = [] # type: List[CoordinateType]
offset = 0
try:
if not self._lines:
# Source text only has whitespaces. We add an empty line
# in order to produce meaningful coordinates.
self._lines = [""]
for row, line in enumerate(self._lines):
assert text[offset : offset + len(line)] == line
col = 0
for _ in line:
self._coords.append((row, col))
offset += 1
col += 1
# All subsequent dropped whitespaces map to the last, imaginary column
# (the EOL character if you wish) of the current line.
while offset < len(text) and text[offset] == " ":
self._coords.append((row, col))
offset += 1
# One past the final character (think of it as EOF) should
# be treated as a valid offset.
self._coords.append((row, col))
except AssertionError:
raise RuntimeError(
"TrackedTextwrap: the impossible happened at offset {} of text {!r}".format(
offset, self._original
)
)
# seq should be a zero-width sequence, e.g., an ANSI escape sequence.
# May raise IndexError if offset is out of bounds.
def insert_zero_width_sequence(self, seq: str, offset: int) -> None:
row, col = self._coords[offset]
line = self._lines[row]
self._lines[row] = line[:col] + seq + line[col:]
# Shift coordinates of all characters after the given character
# on the same line.
shift = len(seq)
offset += 1
while offset < len(self._coords) and self._coords[offset][0] == row:
_, col = self._coords[offset]
self._coords[offset] = (row, col + shift)
offset += 1
@property
def original(self) -> str:
return self._original
@property
def lines(self) -> List[str]:
return self._lines
@property
def wrapped(self) -> str:
return "\n".join(self._lines)
# May raise IndexError if offset is out of bounds.
def get_coordinate(self, offset: int) -> CoordinateType:
return self._coords[offset]
### begin dim (DOM implementation with CSS support) ###
### https://github.com/zmwangx/dim/blob/master/dim.py ###
import html
import re
from collections import OrderedDict
from enum import Enum
from html.parser import HTMLParser
SelectorGroupLike = Union[str, "SelectorGroup", "Selector"]
class Node(object):
"""
Represents a DOM node.
Parts of JavaScript's DOM ``Node`` API and ``Element`` API are
mirrored here, with extensions. In particular, ``querySelector`` and
``querySelectorAll`` are mirrored.
Notable properties and methods: :meth:`attr()`, :attr:`classes`,
:attr:`html`, :attr:`text`, :meth:`ancestors()`,
:meth:`descendants()`, :meth:`select()`, :meth:`select_all()`,
:meth:`matched_by()`,
Attributes:
tag (:class:`Optional`\\[:class:`str`])
attrs (:class:`Dict`\\[:class:`str`, :class:`str`])
parent (:class:`Optional`\\[:class:`Node`])
children (:class:`List`\\[:class:`Node`])
"""
# Meant to be reimplemented by subclasses.
def __init__(self) -> None:
self.tag = None # type: Optional[str]
self.attrs = {} # type: Dict[str, str]
self.parent = None # type: Optional[Node]
self.children = [] # type: List[Node]
# Used in DOMBuilder.
self._partial = False
self._namespace = None # type: Optional[str]
# HTML representation of the node. Meant to be implemented by
# subclasses.
def __str__(self) -> str: # pragma: no cover
raise NotImplementedError
def select(self, selector: SelectorGroupLike) -> Optional["Node"]:
"""DOM ``querySelector`` clone. Returns one match (if any)."""
selector = self._normalize_selector(selector)
for node in self._select_all(selector):
return node
return None
def query_selector(self, selector: SelectorGroupLike) -> Optional["Node"]:
"""Alias of :meth:`select`."""
return self.select(selector)
def select_all(self, selector: SelectorGroupLike) -> List["Node"]:
"""DOM ``querySelectorAll`` clone. Returns all matches in a list."""
selector = self._normalize_selector(selector)
return list(self._select_all(selector))
def query_selector_all(self, selector: SelectorGroupLike) -> List["Node"]:
"""Alias of :meth:`select_all`."""
return self.select_all(selector)
def matched_by(
self, selector: SelectorGroupLike, root: Optional["Node"] = None
) -> bool:
"""
Checks whether this node is matched by `selector`.
See :meth:`SelectorGroup.matches()`.
"""
selector = self._normalize_selector(selector)
return selector.matches(self, root=root)
@staticmethod
def _normalize_selector(selector: SelectorGroupLike) -> "SelectorGroup":
if isinstance(selector, str):
return SelectorGroup.from_str(selector)
if isinstance(selector, SelectorGroup):
return selector
if isinstance(selector, Selector):
return SelectorGroup([selector])
raise ValueError("not a selector or group of selectors: %s" % repr(selector))
def _select_all(self, selector: "SelectorGroup") -> Generator["Node", None, None]:
for descendant in self.descendants():
if selector.matches(descendant, root=self):
yield descendant
def child_nodes(self) -> List["Node"]:
return self.children
def first_child(self) -> Optional["Node"]:
if self.children:
return self.children[0]
else:
return None
def first_element_child(self) -> Optional["Node"]:
for child in self.children:
if isinstance(child, ElementNode):
return child
return None
def last_child(self) -> Optional["Node"]:
if self.children:
return self.children[-1]
else:
return None
def last_element_child(self) -> Optional["Node"]:
for child in reversed(self.children):
if isinstance(child, ElementNode):
return child
return None
def next_sibling(self) -> Optional["Node"]:
""".. note:: Not O(1), use with caution."""
next_siblings = self.next_siblings()
if next_siblings:
return next_siblings[0]
else:
return None
def next_siblings(self) -> List["Node"]:
parent = self.parent
if not parent:
return []
try:
index = parent.children.index(self)
return parent.children[index + 1 :]
except ValueError: # pragma: no cover
raise ValueError("node is not found in children of its parent")
def next_element_sibling(self) -> Optional["ElementNode"]:
""".. note:: Not O(1), use with caution."""
for sibling in self.next_siblings():
if isinstance(sibling, ElementNode):
return sibling
return None
def previous_sibling(self) -> Optional["Node"]:
""".. note:: Not O(1), use with caution."""
previous_siblings = self.previous_siblings()
if previous_siblings:
return previous_siblings[0]
else:
return None
def previous_siblings(self) -> List["Node"]:
"""
Compared to the natural DOM order, the order of returned nodes
are reversed. That is, the adjacent sibling (if any) is the
first in the returned list.
"""
parent = self.parent
if not parent:
return []
try:
index = parent.children.index(self)
if index > 0:
return parent.children[index - 1 :: -1]
else:
return []
except ValueError: # pragma: no cover
raise ValueError("node is not found in children of its parent")
def previous_element_sibling(self) -> Optional["ElementNode"]:
""".. note:: Not O(1), use with caution."""
for sibling in self.previous_siblings():
if isinstance(sibling, ElementNode):
return sibling
return None
def ancestors(
self, *, root: Optional["Node"] = None
) -> Generator["Node", None, None]:
"""
Ancestors are generated in reverse order of depth, stopping at
`root`.
A :class:`RuntimeException` is raised if `root` is not in the
ancestral chain.
"""
if self is root:
return
ancestor = self.parent
while ancestor is not root:
if ancestor is None:
raise RuntimeError("provided root node not found in ancestral chain")
yield ancestor
ancestor = ancestor.parent
if root:
yield root
def descendants(self) -> Generator["Node", None, None]:
"""Descendants are generated in depth-first order."""
for child in self.children:
yield child
yield from child.descendants()
def attr(self, attr: str) -> Optional[str]:
"""Returns the attribute if it exists on the node, otherwise ``None``."""
return self.attrs.get(attr)
@property
def html(self) -> str:
"""
HTML representation of the node.
(For a :class:`TextNode`, :meth:`html` returns the escaped version of the
text.
"""
return str(self)
def outer_html(self) -> str:
"""Alias of :attr:`html`."""
return self.html
def inner_html(self) -> str:
"""HTML representation of the node's children."""
return "".join(child.html for child in self.children)
@property
def text(self) -> str: # pragma: no cover
"""This property is expected to be implemented by subclasses."""
raise NotImplementedError
def text_content(self) -> str:
"""Alias of :attr:`text`."""
return self.text
@property
def classes(self) -> List[str]:
return self.attrs.get("class", "").split()
def class_list(self) -> List[str]:
return self.classes
class ElementNode(Node):
"""
Represents an element node.
Note that tag and attribute names are case-insensitive; attribute
values are case-sensitive.
"""
def __init__(
self,
tag: str,
attrs: Iterable[Tuple[str, Optional[str]]],
*,
parent: Optional["Node"] = None,
children: Optional[Sequence["Node"]] = None
) -> None:
Node.__init__(self)
self.tag = tag.lower() # type: str
self.attrs = OrderedDict((attr.lower(), val or "") for attr, val in attrs)
self.parent = parent
self.children = list(children or [])
def __repr__(self) -> str:
s = "<" + self.tag
if self.attrs:
s += " attrs=%s" % repr(list(self.attrs.items()))
if self.children:
s += " children=%s" % repr(self.children)
s += ">"
return s
# https://ipython.readthedocs.io/en/stable/api/generated/IPython.lib.pretty.html
def _repr_pretty_(self, p: Any, cycle: bool) -> None: # pragma: no cover
if cycle:
raise RuntimeError("cycle detected in DOM tree")
p.text("<\x1b[1m%s\x1b[0m" % self.tag)
if self.attrs:
p.text(" attrs=%s" % repr(list(self.attrs.items())))
if self.children:
p.text(" children=[")
if len(self.children) == 1 and isinstance(self.first_child(), TextNode):
p.text("\x1b[4m%s\x1b[0m" % repr(self.first_child()))
else:
with p.indent(2):
for child in self.children:
p.break_()
if hasattr(child, "_repr_pretty_"):
child._repr_pretty_(p, False) # type: ignore
else:
p.text("\x1b[4m%s\x1b[0m" % repr(child))
p.text(",")
p.break_()
p.text("]")
p.text(">")
def __str__(self) -> str:
"""HTML representation of the node."""
s = "<" + self.tag
for attr, val in self.attrs.items():
s += ' %s="%s"' % (attr, html.escape(val))
if self.children:
s += ">"
s += "".join(str(child) for child in self.children)
s += "</%s>" % self.tag
else:
if _tag_is_void(self.tag):
s += "/>"
else:
s += "></%s>" % self.tag
return s
@property
def text(self) -> str:
"""The concatenation of all descendant text nodes."""
return "".join(child.text for child in self.children)
class TextNode(str, Node):
"""
Represents a text node.
Subclasses :class:`Node` and :class:`str`.
"""
def __new__(cls, text: str) -> "TextNode":
s = str.__new__(cls, text) # type: ignore
s.parent = None
return s # type: ignore
def __init__(self, text: str) -> None:
Node.__init__(self)
def __repr__(self) -> str:
return "<%s>" % str.__repr__(self)
# HTML-escaped form of the text node. use text() for unescaped
# version.
def __str__(self) -> str:
return html.escape(self)
def __eq__(self, other: object) -> bool:
"""
Two text nodes are equal if and only if they are the same node.
For string comparison, use :attr:`text`.
"""
return self is other
def __ne__(self, other: object) -> bool:
"""
Two text nodes are non-equal if they are not the same node.
For string comparison, use :attr:`text`.
"""
return self is not other
@property
def text(self) -> str:
return str.__str__(self)
class DOMBuilderException(Exception):
"""
Exception raised when :class:`DOMBuilder` detects a bad state.
Attributes:
pos (:class:`Tuple`\\[:class:`int`, :class:`int`]):
Line number and offset in HTML input.
why (:class:`str`):
Reason of the exception.
"""
def __init__(self, pos: Tuple[int, int], why: str) -> None:
self.pos = pos
self.why = why
def __str__(self) -> str: # pragma: no cover
return "DOM builder aborted at %d:%d: %s" % (self.pos[0], self.pos[1], self.why)
class DOMBuilder(HTMLParser):
"""
HTML parser / DOM builder.
Subclasses :class:`html.parser.HTMLParser`.
Consume HTML and builds a :class:`Node` tree. Once finished, use
:attr:`root` to access the root of the tree.
This parser cannot parse malformed HTML with tag mismatch.
"""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
# _stack is the stack for nodes. Each node is pushed to the
# stack when its start tag is processed, and remains on the
# stack until its parent node is completed (end tag processed),
# at which point the node is attached to the parent node as a
# child and popped from the stack.
self._stack = [] # type: List[Node]
# _namespace_stack is another stack tracking the parsing
# context, which is generally the default namespace (None) but
# changes when parsing foreign objects (e.g. 'svg' when parsing
# an <svg>). The top element is always the current parsing
# context, so popping works differently from _stack: an element
# is popped as soon as the corresponding end tag is processed.
self._namespace_stack = [None] # type: List[Optional[str]]
def handle_starttag(
self, tag: str, attrs: Sequence[Tuple[str, Optional[str]]]
) -> None:
node = ElementNode(tag, attrs)
node._partial = True
self._stack.append(node)
namespace = (
tag.lower()
if _tag_encloses_foreign_namespace(tag)
else self._namespace_stack[-1] # Inherit parent namespace
)
node._namespace = namespace
self._namespace_stack.append(namespace)
# For void elements (not in a foreign context), immediately
# invoke the end tag handler (see handle_startendtag()).
if not namespace and _tag_is_void(tag):
self.handle_endtag(tag)
def handle_endtag(self, tag: str) -> None:
tag = tag.lower()
children = []
while self._stack and not self._stack[-1]._partial:
children.append(self._stack.pop())
if not self._stack:
raise DOMBuilderException(self.getpos(), "extra end tag: %s" % repr(tag))
parent = self._stack[-1]
if parent.tag != tag:
raise DOMBuilderException(
self.getpos(),
"expecting end tag %s, got %s" % (repr(parent.tag), repr(tag)),
)
parent.children = list(reversed(children))
parent._partial = False
for child in children:
child.parent = parent
self._namespace_stack.pop()
# Make parser behavior for explicitly and implicitly void elements
# (e.g., <hr> vs <hr/>) consistent. The former triggers
# handle_starttag only, whereas the latter triggers
# handle_startendtag (which by default triggers both handle_starttag
# and handle_endtag). See https://bugs.python.org/issue25258.
#
# An exception is foreign elements, which aren't considered void
# elements but can be explicitly marked as self-closing according to
# the HTML spec (e.g. <path/> is valid but <path> is not).
# Therefore, both handle_starttag and handle_endtag must be called,
# and handle_endtag should not be triggered from within
# handle_starttag in that case.
#
# Note that for simplicity we do not check whether the foreign
# element in question is allowed to be self-closing by spec. (The
# SVG spec unfortunately doesn't provide a readily available list of
# such elements.)
#
# https://html.spec.whatwg.org/multipage/syntax.html#foreign-elements
def handle_startendtag(
self, tag: str, attrs: Sequence[Tuple[str, Optional[str]]]
) -> None:
if self._namespace_stack[-1] or _tag_encloses_foreign_namespace(tag):
self.handle_starttag(tag, attrs)
self.handle_endtag(tag)
else:
self.handle_starttag(tag, attrs)
def handle_data(self, text: str) -> None:
if not self._stack:
# Ignore text nodes before the first tag.
return
self._stack.append(TextNode(text))
@property
def root(self) -> "Node":
"""
Finishes processing and returns the root node.
Raises :class:`DOMBuilderException` if there is no root tag or
root tag is not closed yet.
"""
if not self._stack:
raise DOMBuilderException(self.getpos(), "no root tag")
if self._stack[0]._partial:
raise DOMBuilderException(self.getpos(), "root tag not closed yet")
return self._stack[0]
def parse_html(html: str, *, ParserClass: type = DOMBuilder) -> "Node":
"""
Parses HTML string, builds DOM, and returns root node.
The parser may raise :class:`DOMBuilderException`.
Args:
html: input HTML string
ParserClass: :class:`DOMBuilder` or a subclass
Returns:
Root note of the parsed tree. If the HTML string contains
multiple top-level elements, only the first is returned and the
rest are lost.
"""
builder = ParserClass() # type: DOMBuilder
builder.feed(html)
builder.close()
return builder.root
class SelectorParserException(Exception):
"""
Exception raised when the selector parser fails to parse an input.
Attributes:
s (:class:`str`):
The input string to be parsed.
cursor (:class:`int`):
Cursor position where the failure occurred.
why (:class:`str`):
Reason of the failure.
"""
def __init__(self, s: str, cursor: int, why: str) -> None:
self.s = s
self.cursor = cursor
self.why = why
def __str__(self) -> str: # pragma: no cover
return "selector parser aborted at character %d of %s: %s" % (
self.cursor,
repr(self.s),
self.why,
)
class SelectorGroup:
"""
Represents a group of CSS selectors.
A group of CSS selectors is simply a comma-separated list of
selectors. [#]_ See :class:`Selector` documentation for the scope of
support.
Typically, a :class:`SelectorGroup` is constructed from a string
(e.g., ``th.center, td.center``) using the factory function
:meth:`from_str`.
.. [#] https://www.w3.org/TR/selectors-3/#grouping
"""
def __init__(self, selectors: Iterable["Selector"]) -> None:
self._selectors = list(selectors)
def __repr__(self) -> str:
return "<SelectorGroup %s>" % repr(str(self))
def __str__(self) -> str:
return ", ".join(str(selector) for selector in self._selectors)
def __len__(self) -> int:
return len(self._selectors)
def __getitem__(self, index: int) -> "Selector":
return self._selectors[index]
def __iter__(self) -> Iterator["Selector"]:
return iter(self._selectors)
@classmethod
def from_str(cls, s: str) -> "SelectorGroup":
"""
Parses input string into a group of selectors.
:class:`SelectorParserException` is raised on invalid input. See
:class:`Selector` documentation for the scope of support.
Args:
s: input string
Returns:
Parsed group of selectors.
"""
i = 0
selectors = []
while i < len(s):
selector, i = Selector.from_str(s, i)
selectors.append(selector)
if not selectors:
raise SelectorParserException(s, i, "selector group is empty")
return cls(selectors)
def matches(self, node: "Node", root: Optional["Node"] = None) -> bool:
"""
Decides whether the group of selectors matches `node`.
The group of selectors matches `node` as long as one of the
selectors matches `node`.
If `root` is provided and child and/or descendant combinators
are involved, parent/ancestor lookup terminates at `root`.
"""
return any(selector.matches(node, root=root) for selector in self)
class Selector:
"""
Represents a CSS selector.
Recall that a CSS selector is a chain of one or more *sequences of
simple selectors* separated by *combinators*. [#selectors-3]_ This
concept is represented as a cons list of sequences of simple
selectors (in right to left order). This class in fact holds a
single sequence, with an optional combinator and reference to the
previous sequence.
For instance, ``main#main p.important.definition >
a.term[id][href]`` would be parsed into (schematically) the
following structure::
">" tag='a' classes=('term') attrs=([id], [href]) ~>
" " tag='p' classes=('important', 'definition') ~>
tag='main' id='main'
Each line is held in a separate instance of :class:`Selector`,
linked together by the :attr:`previous` attribute.
Supported grammar (from selectors level 3 [#selectors-3]_):
- Type selectors;
- Universal selectors;
- Class selectors;
- ID selectors;
- Attribute selectors;
- Combinators.
Unsupported grammar:
- Pseudo-classes;
- Pseudo-elements;
- Namespace prefixes (``ns|``, ``*|``, ``|``) in any part of any
selector.
Rationale:
- Pseudo-classes have too many variants, a few of which even
complete with an admittedly not-so-complex minilanguage. These add
up to a lot of code.
- Pseudo-elements are useless outside rendering contexts, hence out of
scope.
- Namespace support is too niche to be worth the parsing headache.
*Using namespace prefixes may confuse the parser!*
Note that the parser only loosely follows the spec and priotizes
ease of parsing (which includes readability and *writability* of
regexes), so some invalid selectors may be accepted (in fact, false
positives abound, but accepting valid inputs is a much more
important goal than rejecting invalid inputs for this library), and
some valid selectors may be rejected (but as long as you stick to
the scope outlined above and common sense you should be fine; the
false negatives shouldn't be used by actual human beings anyway).
In particular, whitespace character is simplified to ``\\s`` (ASCII
mode) despite CSS spec not counting U+000B (VT) as whitespace,
identifiers are simplified to ``[\\w-]+`` (ASCII mode), and strings
(attribute selector values can be either identifiers or strings)
allow escaped quotes (i.e., ``\\'`` inside single-quoted strings and
``\\"`` inside double-quoted strings) but everything else is
interpreted literally. The exact specs for CSS identifiers and
strings can be found at [#]_.
Certain selectors and combinators may be implemented in the parser
but not implemented in matching and/or selection APIs.
.. [#selectors-3] https://www.w3.org/TR/selectors-3/
.. [#] https://www.w3.org/TR/CSS21/syndata.html
Attributes:
tag (:class:`Optional`\\[:class:`str`]):
Type selector.
classes (:class:`List`\\[:class:`str`]):
Class selectors.
id (:class:`Optional`\\[:class:`str`]):
ID selector.
attrs (:class:`List`\\[:class:`AttributeSelector`]):
Attribute selectors.
combinator (:class:`Optional`\\[:class:`Combinator`]):
Combinator with the previous sequence of simple selectors in
chain.
previous (:class:`Optional`\\[:class:`Selector`]):
Reference to the previous sequence of simple selectors in
chain.
"""
def __init__(
self,
*,
tag: Optional[str] = None,
classes: Optional[Sequence[str]] = None,
id: Optional[str] = None,
attrs: Optional[Sequence["AttributeSelector"]] = None,
combinator: Optional["Combinator"] = None,
previous: Optional["Selector"] = None
) -> None:
self.tag = tag.lower() if tag else None
self.classes = list(classes or [])
self.id = id
self.attrs = list(attrs or [])
self.combinator = combinator
self.previous = previous
def __repr__(self) -> str:
return "<Selector %s>" % repr(str(self))
def __str__(self) -> str:
sequences = []
delimiters = []
seq = self
while True:
sequences.append(seq._sequence_str_())
if seq.previous:
if seq.combinator == Combinator.DESCENDANT:
delimiters.append(" ")
elif seq.combinator == Combinator.CHILD:
delimiters.append(" > ")