forked from jarun/ddgr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathddgr
executable file
·2138 lines (1782 loc) · 70.1 KB
/
ddgr
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 (C) 2016-2025 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 codecs
import collections
import functools
import gzip
import html.entities
import html.parser
import json
import locale
import logging
import os
import platform
import shutil
import signal
from subprocess import Popen, PIPE, DEVNULL
import sys
import tempfile
import textwrap
import unicodedata
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
try:
import readline
except ImportError:
pass
try:
import setproctitle
setproctitle.setproctitle('ddgr')
except (ImportError, Exception):
pass
# Basic setup
logging.basicConfig(format='[%(levelname)s] %(message)s')
LOGGER = logging.getLogger()
LOGDBG = LOGGER.debug
LOGERR = LOGGER.error
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_ = '2.2'
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 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
TEXT_BROWSERS = ['elinks', 'links', 'lynx', 'w3m', 'www-browser']
INDENT = 5
# Global helper functions
def open_url(url):
"""Open an URL in the user's default web browser.
The string attribute ``open_url.url_handler`` can be used to open URLs
in a custom CLI script or utility. A subprocess is spawned with url as
the parameter in this case instead of the usual webbrowser.open() call.
Whether the browser's output (both stdout and stderr) are suppressed
depends on the boolean attribute ``open_url.suppress_browser_output``.
If the attribute is not set upon a call, set it to a default value,
which means False if BROWSER is set to a known text-based browser --
elinks, links, lynx, w3m or 'www-browser'; or True otherwise.
The string attribute ``open_url.override_text_browser`` can be used to
ignore env var BROWSER as well as some known text-based browsers and
attempt to open url in a GUI browser available.
Note: If a GUI browser is indeed found, this option ignores the program
option `show-browser-logs`
"""
LOGDBG('Opening %s', url)
# Custom URL handler gets max priority
if hasattr(open_url, 'url_handler'):
with Popen([open_url.url_handler, url], stdin=PIPE) as pipe:
pipe.communicate()
return
browser = webbrowser.get()
if open_url.override_text_browser:
browser_output = open_url.suppress_browser_output
for name in [b for b in webbrowser._tryorder if b not in TEXT_BROWSERS]:
browser = webbrowser.get(name)
LOGDBG(browser)
# Found a GUI browser, suppress browser output
open_url.suppress_browser_output = True
break
if open_url.suppress_browser_output:
_stderr = os.dup(2)
os.close(2)
_stdout = os.dup(1)
if "microsoft" not in platform.uname()[3].lower():
os.close(1)
fd = os.open(os.devnull, os.O_RDWR)
os.dup2(fd, 2)
os.dup2(fd, 1)
try:
browser.open(url, new=2)
finally:
if open_url.suppress_browser_output:
os.close(fd)
os.dup2(_stderr, 2)
os.dup2(_stdout, 1)
if open_url.override_text_browser:
open_url.suppress_browser_output = browser_output
def https_get(url, headers=None, proxies=None, expected_code=None):
"""Sends an HTTPS GET request; returns the HTTP status code and the
decoded response payload.
By default, HTTP 301, 302 and 303 are followed; all other non-2XX
responses result in a urllib.error.HTTPError. If expected_code is
supplied, a urllib.error.HTTPError is raised unless the status code
matches expected_code.
"""
headers = headers or {}
proxies = {'https': proxies['https']} if proxies.get('https') else {}
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler,
urllib.request.ProxyHandler(proxies),
urllib.request.HTTPRedirectHandler,
)
req = urllib.request.Request(
url,
)
resp = opener.open(req)
code = resp.getcode()
if expected_code is not None and code != expected_code:
raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp)
payload = resp.read()
try:
payload = gzip.decompress(payload)
except OSError:
pass
finally:
payload = payload.decode('utf-8')
return code, payload
def https_post(url, data=None, headers=None, proxies=None, expected_code=None):
"""Sends an HTTPS POST request; returns the HTTP status code and the
decoded response payload.
By default, HTTP 301, 302 and 303 are followed; all other non-2XX
responses result in a urllib.error.HTTPError. If expected_code is
supplied, a urllib.error.HTTPError is raised unless the status code
matches expected_code.
"""
data = data or {}
headers = headers or {}
proxies = {'https': proxies['https']} if proxies.get('https') else {}
opener = urllib.request.build_opener(
urllib.request.HTTPSHandler,
urllib.request.ProxyHandler(proxies),
urllib.request.HTTPRedirectHandler,
)
req = urllib.request.Request(
url,
data=urllib.parse.urlencode(data).encode('ascii'),
headers=headers,
)
resp = opener.open(req)
code = resp.getcode()
if expected_code is not None and code != expected_code:
raise urllib.error.HTTPError(resp.geturl(), code, resp.msg, resp.info(), resp)
payload = resp.read()
try:
payload = gzip.decompress(payload)
except OSError:
pass
finally:
payload = payload.decode('utf-8')
return code, payload
def unwrap(text):
"""Unwrap text."""
lines = text.split('\n')
result = ''
for i in range(len(lines) - 1):
result += lines[i]
if not lines[i]:
# Paragraph break
result += '\n\n'
elif lines[i + 1]:
# Next line is not paragraph break, add space
result += ' '
# Handle last line
result += lines[-1] if lines[-1] else '\n'
return result
def check_stdout_encoding():
"""Make sure stdout encoding is utf-8.
If not, print error message and instructions, then exit with
status 1.
This function is a no-op on win32 because encoding on win32 is
messy, and let's just hope for the best. /s
"""
if sys.platform == 'win32':
return
# Use codecs.lookup to resolve text encoding alias
encoding = codecs.lookup(sys.stdout.encoding).name
if encoding != 'utf-8':
locale_lang, locale_encoding = locale.getlocale()
if locale_lang is None:
locale_lang = '<unknown>'
if locale_encoding is None:
locale_encoding = '<unknown>'
ioencoding = os.getenv('PYTHONIOENCODING', 'not set')
sys.stderr.write(unwrap(textwrap.dedent("""\
stdout encoding '{encoding}' detected. ddgr requires utf-8 to
work properly. The wrong encoding may be due to a non-UTF-8
locale or an improper PYTHONIOENCODING. (For the record, your
locale language is {locale_lang} and locale encoding is
{locale_encoding}; your PYTHONIOENCODING is {ioencoding}.)
Please set a UTF-8 locale (e.g., en_US.UTF-8) or set
PYTHONIOENCODING to utf-8.
""".format(
encoding=encoding,
locale_lang=locale_lang,
locale_encoding=locale_encoding,
ioencoding=ioencoding,
))))
sys.exit(1)
def printerr(msg):
"""Print message, verbatim, to stderr.
``msg`` could be any stringifiable value.
"""
print(msg, file=sys.stderr)
# 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):
width = max(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()
# Classes
class DdgUrl:
"""
This class constructs the DuckDuckGo Search/News URL.
This class is modeled on urllib.parse.ParseResult for familiarity,
which means it supports reading of all six attributes -- scheme,
netloc, path, params, query, fragment -- of
urllib.parse.ParseResult, as well as the geturl() method.
However, the attributes (properties) and methods listed below should
be the preferred methods of access to this class.
Parameters
----------
opts : dict or argparse.Namespace, optional
See the ``opts`` parameter of `update`.
Other Parameters
----------------
See "Other Parameters" of `update`.
Attributes
----------
hostname : str
Read-write property.
keywords : str or list of strs
Read-write property.
news : bool
Read-only property.
url : str
Read-only property.
Methods
-------
full()
update(opts=None, **kwargs)
set_queries(**kwargs)
unset_queries(*args)
next_page()
prev_page()
first_page()
"""
def __init__(self, opts=None, **kwargs):
self.scheme = 'https'
# self.netloc is a calculated property
self.path = '/html/'
self.params = ''
# self.query is a calculated property
self.fragment = ''
self._duration = '' # duration as day, week, month or unlimited
self._region = '' # Region code
self._qrycnt = 0 # Number of search results fetched in most recent query
self._curindex = 1 # Index of total results in pages fetched so far + 1
self._page = 0 # Current page number
self._keywords = []
self._sites = None
self._safe = 1 # Safe search parameter value
self.np_prev = '' # nextParams from last html page Previous button
self.np_next = '' # nextParams from last html page Next button
self.vqd = '' # vqd parameter (from next/prev button)
self._query_dict = {
}
self.update(opts, **kwargs)
def __str__(self):
return self.url
@property
def url(self):
"""The full DuckDuckGo URL you want."""
return self.full()
@property
def hostname(self):
"""The hostname."""
return self.netloc
@hostname.setter
def hostname(self, hostname):
self.netloc = hostname
@property
def keywords(self):
"""The keywords, either a str or a list of strs."""
return self._keywords
@keywords.setter
def keywords(self, keywords):
self._keywords = keywords
@property
def news(self):
"""Whether the URL is for DuckDuckGo News."""
return 'tbm' in self._query_dict and self._query_dict['tbm'] == 'nws'
def full(self):
"""Return the full URL.
Returns
-------
str
"""
q = ''
if self._keywords:
if isinstance(self._keywords, list):
q += '+'.join(list(self._keywords))
else:
q += self._keywords
url = (self.scheme + ':') if self.scheme else ''
url += '//' + self.netloc + '/?q=' + q
return url
def update(self, opts=None, **kwargs):
"""Update the URL with the given options.
Parameters
----------
opts : dict or argparse.Namespace, optional
Carries options that affect the DuckDuckGo Search/News URL. The
list of currently recognized option keys with expected value
types:
keywords: str or list of strs
num: int
Other Parameters
----------------
kwargs
The `kwargs` dict extends `opts`, that is, options can be
specified either way, in `opts` or as individual keyword
arguments.
"""
if opts is None:
opts = {}
if hasattr(opts, '__dict__'):
opts = opts.__dict__
opts.update(kwargs)
if 'keywords' in opts:
self._keywords = opts['keywords']
self._duration = opts['duration']
if 'region' in opts:
self._region = opts['region']
if 'num' in opts:
self._qrycnt = 0
if 'sites' in opts:
self._sites = opts['sites']
if 'unsafe' in opts and opts['unsafe']:
self._safe = -2
def set_queries(self, **kwargs):
"""Forcefully set queries outside the normal `update` mechanism.
Other Parameters
----------------
kwargs
Arbitrary key value pairs to be set in the query string. All
keys and values should be stringifiable.
Note that certain keys, e.g., ``q``, have their values
constructed on the fly, so setting those has no actual
effect.
"""
for k, v in kwargs.items():
self._query_dict[k] = v
def unset_queries(self, *args):
"""Forcefully unset queries outside the normal `update` mechanism.
Other Parameters
----------------
args
Arbitrary keys to be unset. No exception is raised if a key
does not exist in the first place.
Note that certain keys, e.g., ``q``, are always included in
the resulting URL, so unsetting those has no actual effect.
"""
for k in args:
self._query_dict.pop(k, None)
def next_page(self):
"""Navigate to the next page."""
self._page = self._page + 1
if self._curindex > 0:
self._curindex = self._curindex + self._qrycnt
else:
self._curindex = -self._curindex
def prev_page(self):
"""Navigate to the previous page.
Raises
------
ValueError
If already at the first page (``page=0`` in the current
query string).
"""
if self._page == 0:
raise ValueError('Already at the first page.')
self._page = self._page - 1
if self._curindex > 0:
self._curindex = -self._curindex # A negative index is used when fetching previous page
else:
self._curindex = self._curindex + self._qrycnt
def first_page(self):
"""Navigate to the first page.
Raises
------
ValueError
If already at the first page (``page=0`` in the current
query string).
"""
if self._page == 0:
raise ValueError('Already at the first page.')
self._page = 0
self._qrycnt = 0
self._curindex = 1
@property
def netloc(self):
"""The hostname."""
return 'duckduckgo.com'
def query(self):
"""The query string."""
qd = {}
qd.update(self._query_dict)
qd['duration'] = self._duration
qd['region'] = self._region
qd['curindex'] = self._curindex
qd['page'] = self._page
qd['safe'] = self._safe
if self._curindex < 0:
qd['nextParams'] = self.np_prev
else:
qd['nextParams'] = self.np_next
qd['vqd'] = self.vqd
# Construct the q query
q = ''
keywords = self._keywords
sites = self._sites
if keywords:
if isinstance(keywords, list):
q += ' '.join(list(keywords))
else:
q += keywords
if sites:
q += ' site:' + ','.join(urllib.parse.quote_plus(site) for site in sites)
qd['q'] = q
return qd
def update_num(self, count):
self._qrycnt = count
class DdgAPIUrl:
"""
This class constructs the DuckDuckGo Instant Answer API URL.
Attributes
----------
hostname : str
Read-write property.
keywords : str or list of strs
Read-write property.
url : str
Read-only property.
netloc : str
Read-only property.
Methods
-------
full()
"""
def __init__(self, keywords):
self.scheme = 'https'
self.path = '/'
self.params = ''
self._format = 'format=json'
self._keywords = keywords
def __str__(self):
return self.url
@property
def url(self):
"""The full DuckDuckGo URL you want."""
return self.full()
@property
def hostname(self):
"""The hostname."""
return self.netloc
@hostname.setter
def hostname(self, hostname):
self.netloc = hostname
@property
def keywords(self):
"""The keywords, either a str or a list of strs."""
return self._keywords
@keywords.setter
def keywords(self, keywords):
self._keywords = keywords
@property
def netloc(self):
"""The hostname."""
return 'api.duckduckgo.com'
def full(self):
"""Return the full URL.
Returns
-------
str
"""
q = ''
if self._keywords:
if isinstance(self._keywords, list):
q += '+'.join(list(self._keywords))
else:
q += self._keywords
url = (self.scheme + ':') if self.scheme else ''
url += '//' + self.netloc + '/?q=' + q + "&" + self._format
return url
class DDGConnectionError(Exception):
pass
class DdgConnection:
"""
This class facilitates connecting to and fetching from DuckDuckGo.
Parameters
----------
See http.client.HTTPSConnection for documentation of the
parameters.
Raises
------
DDGConnectionError
Methods
-------
fetch_page(url)
"""
def __init__(self, proxy=None, ua=''):
self._u = 'https://html.duckduckgo.com/html'
self._proxies = {
'https': proxy if proxy is not None else (os.getenv('https_proxy')
if os.getenv('https_proxy') is not None
else os.getenv('HTTPS_PROXY'))
}
self._ua = ua
def fetch_page(self, url):
"""Fetch a URL.
Allows one reconnection and one redirection before failing and
raising DDGConnectionError.
Parameters
----------
url : str
The URL to fetch, relative to the host.
Raises
------
DDGConnectionError
When not getting HTTP 200 even after the allowed one
reconnection and/or one redirection, or when DuckDuckGo is
blocking query due to unusual activity.
Returns
-------
str
Response payload, gunzipped (if applicable) and decoded (in UTF-8).
"""
dic = url.query()
page = dic['page']
LOGDBG('q:%s, region:%s, page:%d, curindex:%d, safe:%d', dic['q'], dic['region'], page, dic['curindex'], dic['safe'])
LOGDBG('nextParams:%s', dic['nextParams'])
LOGDBG('vqd:%s', dic['vqd'])
LOGDBG('proxy:%s', self._proxies)
LOGDBG('ua:%s', self._ua)
try:
if page == 0:
_, r = https_post(self._u,
headers={
'Accept-Encoding': 'gzip',
'User-Agent': self._ua,
'DNT': '1',
},
data={
'q': dic['q'],
'b': '',
'df': dic['duration'],
'kf': '-1',
'kh': '1',
'kl': dic['region'],
'kp': dic['safe'],
'k1': '-1',
},
proxies=self._proxies,
expected_code=200)
else:
_, r = https_post(self._u,
headers={
'Accept-Encoding': 'gzip',
'User-Agent': self._ua,
'DNT': '1',
},
data={
'q': dic['q'], # The query string
's': str(50 * (page - 1) + 30), # Page index
'nextParams': dic['nextParams'], # nextParams from last visited page
'v': 'l',
'o': 'json',
'dc': str(dic['curindex']), # Start from total fetched result index
'df': dic['duration'],
'api': '/d.js',
'kf': '-1', # Disable favicons
'kh': '1', # HTTPS always ON
'kl': dic['region'], # Region code
'kp': dic['safe'], # Safe search
'k1': '-1', # Advertisements off
'vqd': dic['vqd'], # vqd string from button
},
proxies=self._proxies,
expected_code=200)
except Exception as e:
LOGERR(e)
return None
return r
def annotate_tag(annotated_starttag_handler):
# See parser logic within the DdgParser class for documentation.
#
# annotated_starttag_handler(self, tag: str, attrsdict: dict) -> annotation
# Returns: HTMLParser.handle_starttag(self, tag: str, attrs: list) -> None
def handler(self, tag, attrs):
attrs = dict(attrs)
annotation = annotated_starttag_handler(self, tag, attrs)
self.insert_annotation(tag, annotation)
return handler
def retrieve_tag_annotation(annotated_endtag_handler):
# See parser logic within the DdgParser class for documentation.
#
# annotated_endtag_handler(self, tag: str, annotation) -> None
# Returns: HTMLParser.handle_endtag(self, tag: str) -> None
def handler(self, tag):
try:
annotation = self.tag_annotations[tag].pop()
except IndexError:
# Malformed HTML -- more close tags than open tags
annotation = None
annotated_endtag_handler(self, tag, annotation)
return handler
class DdgParser(html.parser.HTMLParser):
"""The members of this class parse the result HTML
page fetched from DuckDuckGo server for a query.
The custom parser looks for tags enclosing search
results and extracts the URL, title and text for
each search result.
After parsing the complete HTML page results are
returned in a list of objects of class Result.
"""
# Parser logic:
#
# - Guiding principles:
#
# 1. Tag handlers are contextual;
#
# 2. Contextual starttag and endtag handlers should come in pairs
# and have a clear hierarchy;
#
# 3. starttag handlers should only yield control to a pair of
# child handlers (that is, one level down the hierarchy), and
# correspondingly, endtag handlers should only return control
# to the parent (that is, the pair of handlers that gave it
# control in the first place).
#
# Principle 3 is meant to enforce a (possibly implicit) stack
# structure and thus prevent careless jumps that result in what's
# essentially spaghetti code with liberal use of GOTOs.
#
# - HTMLParser.handle_endtag gives us a bare tag name without
# context, which is not good for enforcing principle 3 when we
# have, say, nested div tags.
#
# In order to precisely identify the matching opening tag, we
# maintain a stack for each tag name with *annotations*. Important
# opening tags (e.g., the ones where child handlers are
# registered) can be annotated so that when we can watch for the
# annotation in the endtag handler, and when the appropriate
# annotation is popped, we perform the corresponding action (e.g.,
# switch back to old handlers).
#
# To facilitate this, each starttag handler is decorated with
# @annotate_tag, which accepts a return value that is the
# annotation (None by default), and additionally converts attrs to
# a dict, which is much easier to work with; and each endtag
# handler is decorated with @retrieve_tag_annotation which sends
# an additional parameter that is the retrieved annotation to the
# handler.
#
# Note that some of our tag annotation stacks leak over time: this
# happens to tags like <img> and <hr> which are not
# closed. However, these tags play no structural role, and come
# only in small quantities, so it's not really a problem.
#
# - All textual data (result title, result abstract, etc.) are
# processed through a set of shared handlers. These handlers store
# text in a shared buffer self.textbuf which can be retrieved and
# cleared at appropriate times.
#
# Data (including charrefs and entityrefs) are ignored initially,
# and when data needs to be recorded, the start_populating_textbuf
# method is called to register the appropriate data, charref and
# entityref handlers so that they append to self.textbuf. When
# recording ends, pop_textbuf should be called to extract the text
# and clear the buffer. stop_populating_textbuf returns the
# handlers to their pristine state (ignoring data).
#
# Methods:
# - start_populating_textbuf(self, data_transformer: Callable[[str], str]) -> None
# - pop_textbuf(self) -> str
# - stop_populating_textbuf(self) -> None
#
# - Outermost starttag and endtag handler methods: root_*. The whole
# parser starts and ends in this state.
#
# - Each result is wrapped in a <div> tag with class "links_main".
#
# <!-- within the scope of root_* -->
# <div class="links_main"> <!-- annotate as 'result', hand over to result_* -->
# </div> <!-- hand back to root_*, register result -->
#
# - For each result, the first <h2> tag with class "result__title" contains the
# hyperlinked title.
#
# <!-- within the scope of result_* -->
# <h2 class="result__title"> <!-- annotate as 'title', hand over to title_* -->
# </h2> <!-- hand back to result_* -->
#
# - Abstracts are within the scope of <div> tag with class "links_main". Links in
# abstract are ignored as they are available within <h2> tag.
#
# <!-- within the scope of result_* -->
# <a class="result__snippet"> <!-- annotate as 'abstract', hand over to abstract_* -->
# </a> <!-- hand back to result_* -->
#
# - Each title looks like
#
# <h2 class="result__title">
# <!-- within the scope of title_* -->
# <a href="result url"> <!-- register self.url, annotate as 'title_link',
# start_populating_textbuf -->
# result title
# <span> <!-- filetype (optional), annotate as title_filetype,
# start_populating_textbuf -->
# file type (e.g. [PDF])
# </span> <!-- stop_populating_textbuf, update self.filetype,
# start_populating_tetbuf -->
# </a> <!-- stop_populating_textbuf, pop to self.title
# prepend self.filetype, if available -->
# </h2>
def __init__(self, offset=0):
html.parser.HTMLParser.__init__(self)
self.title = ''
self.url = ''
self.abstract = ''
self.filetype = ''
self.results = []
self.index = offset
self.textbuf = ''
self.click_result = ''
self.tag_annotations = {}
self.np_prev_button = ''
self.np_next_button = ''
self.npfound = False # First next params found
self.set_handlers_to('root')
self.vqd = '' # vqd returned from button, required for search query to get next set of results
# Tag handlers
@annotate_tag
def root_start(self, tag, attrs):
if tag == 'div':
if 'zci__result' in self.classes(attrs):
self.start_populating_textbuf()
return 'click_result'
if 'links_main' in self.classes(attrs):
# Initialize result field registers
self.title = ''
self.url = ''
self.abstract = ''
self.filetype = ''
self.set_handlers_to('result')
return 'result'
if 'nav-link' in self.classes(attrs):
self.set_handlers_to('input')
return 'input'
return ''
@retrieve_tag_annotation
def root_end(self, tag, annotation):
if annotation == 'click_result':
self.stop_populating_textbuf()
self.click_result = self.pop_textbuf()
self.set_handlers_to('root')
@annotate_tag
def result_start(self, tag, attrs):
if tag == 'h2' and 'result__title' in self.classes(attrs):
self.set_handlers_to('title')
return 'title'