forked from jarun/googler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgoogler
executable file
·2367 lines (2019 loc) · 81.4 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-2017 Arun Prakash Jana <engineerarun@gmail.com>
#
# 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 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 signal
import socket
import ssl
import sys
import textwrap
import urllib.parse
import webbrowser
# Python optional dependency compatibility layer
try:
import readline
except ImportError:
pass
# Basic setup
try:
import setproctitle
setproctitle.setproctitle('googler')
except Exception:
pass
logging.basicConfig(format='[%(levelname)s] %(message)s')
logger = logging.getLogger()
def sigint_handler(signum, frame):
print('\nInterrupted.', file=sys.stderr)
sys.exit(1)
signal.signal(signal.SIGINT, sigint_handler)
# Constants
_VERSION_ = '3.0'
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()}
# Disguise as Firefox on Ubuntu
USER_AGENT = ('Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:52.0) Gecko/20100101 Firefox/52.0')
ua = True # User Agent is enabled by default
# 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'
# Global helper functions
def open_url(url):
"""Open an URL in the user's default web browser.
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 or w3m; or True otherwise.
"""
if not hasattr(open_url, 'suppress_browser_output'):
open_url.suppress_browser_output = (os.getenv('BROWSER') not in
['elinks', 'links', 'lynx', 'w3m'])
logger.debug('Opening %s', url)
if open_url.suppress_browser_output:
_stderr = os.dup(2)
os.close(2)
_stdout = os.dup(1)
os.close(1)
fd = os.open(os.devnull, os.O_RDWR)
os.dup2(fd, 2)
os.dup2(fd, 1)
try:
webbrowser.open(url)
finally:
if open_url.suppress_browser_output:
os.close(fd)
os.dup2(_stderr, 2)
os.dup2(_stdout, 1)
def printerr(msg):
"""Print message, verbatim, to stderr.
``msg`` could be any stringifiable value.
"""
print(msg, file=sys.stderr)
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. googler 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)
# Classes
class TLS1_2Connection(HTTPSConnection):
"""Overrides HTTPSConnection.connect to specify TLS version
NOTE: TLS 1.2 is supported from Python 3.4
"""
def __init__(self, host, **kwargs):
HTTPSConnection.__init__(self, host, **kwargs)
def connect(self, notweak=False):
sock = socket.create_connection((self.host, self.port),
self.timeout, self.source_address)
# Optimizations not available on OS X
if not notweak and sys.platform.startswith('linux'):
sock.setsockopt(socket.SOL_TCP, socket.TCP_DEFER_ACCEPT, 1)
sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 524288)
if getattr(self, '_tunnel_host', None):
self.sock = sock
elif not notweak:
# Try to use TLS 1.2
ssl_context = None
if hasattr(ssl, 'PROTOCOL_TLS'):
# Since Python 3.5.3
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
elif hasattr(ssl, 'PROTOCOL_TLSv1_2'):
# Since Python 3.4
ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
if ssl_context:
self.sock = ssl_context.wrap_socket(sock)
return
# Fallback
HTTPSConnection.connect(self)
class GoogleUrl(object):
"""
This class constructs the Google Search/News URL.
This class is modelled 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()
relative()
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 = '/search'
self.params = ''
# self.query is a calculated property
self.fragment = ''
self._tld = None
self._num = 10
self._start = 0
self._keywords = []
self._site = None
self._query_dict = {
'ie': 'UTF-8',
'oe': 'UTF-8',
}
self.update(opts, **kwargs)
def __str__(self):
return self.url
@property
def url(self):
"""The full Google 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 Google News."""
return 'tbm' in self._query_dict and self._query_dict['tbm'] == 'nws'
def full(self):
"""Return the full URL.
Returns
-------
str
"""
url = (self.scheme + ':') if self.scheme else ''
url += '//' + self.netloc + self.relative()
return url
def relative(self):
"""Return the relative URL (without scheme and authority).
Authority (see RFC 3986 section 3.2), or netloc in the
terminology of urllib.parse, basically means the hostname
here. The relative URL is good for making HTTP(S) requests to a
known host.
Returns
-------
str
"""
rel = self.path
if self.params:
rel += ';' + self.params
if self.query:
rel += '?' + self.query
if self.fragment:
rel += '#' + self.fragment
return rel
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 Google Search/News URL. The
list of currently recognized option keys with expected value
types:
duration: str (GooglerArgumentParser.is_duration)
exact: bool
keywords: str or list of strs
lang: str
news: bool
num: int
site: str
start: int
tld: str
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)
qd = self._query_dict
if 'duration' in opts and opts['duration']:
qd['tbs'] = 'qdr:%s' % opts['duration']
if 'exact' in opts:
if opts['exact']:
qd['nfpr'] = 1
else:
qd.pop('nfpr', None)
if 'keywords' in opts:
self._keywords = opts['keywords']
if 'lang' in opts and opts['lang']:
qd['hl'] = opts['lang']
if 'news' in opts:
if opts['news']:
qd['tbm'] = 'nws'
else:
qd.pop('tbm', None)
if 'num' in opts:
self._num = opts['num']
if 'site' in opts:
self._site = opts['site']
if 'start' in opts:
self._start = opts['start']
if 'tld' in opts:
self._tld = opts['tld']
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._start += self._num
def prev_page(self):
"""Navigate to the previous page.
Raises
------
ValueError
If already at the first page (``start=0`` in the current
query string).
"""
if self._start == 0:
raise ValueError('Already at the first page.')
self._start = (self._start - self._num) if self._start > self._num else 0
def first_page(self):
"""Navigate to the first page.
Raises
------
ValueError
If already at the first page (``start=0`` in the current
query string).
"""
if self._start == 0:
raise ValueError('Already at the first page.')
self._start = 0
# Data source: https://en.wikipedia.org/wiki/List_of_Google_domains
# Scraper script: https://gist.github.com/zmwangx/b976e83c14552fe18b71
TLD_TO_DOMAIN_MAP = {
'ac': 'google.ac', 'ad': 'google.ad', 'ae': 'google.ae',
'af': 'google.com.af', 'ag': 'google.com.ag', 'ai': 'google.com.ai',
'al': 'google.al', 'am': 'google.am', 'ao': 'google.co.ao',
'ar': 'google.com.ar', 'as': 'google.as', 'at': 'google.at',
'au': 'google.com.au', 'az': 'google.az', 'ba': 'google.ba',
'bd': 'google.com.bd', 'be': 'google.be', 'bf': 'google.bf',
'bg': 'google.bg', 'bh': 'google.com.bh', 'bi': 'google.bi',
'bj': 'google.bj', 'bn': 'google.com.bn', 'bo': 'google.com.bo',
'br': 'google.com.br', 'bs': 'google.bs', 'bt': 'google.bt',
'bw': 'google.co.bw', 'by': 'google.by', 'bz': 'google.com.bz',
'ca': 'google.ca', 'cat': 'google.cat', 'cc': 'google.cc',
'cd': 'google.cd', 'cf': 'google.cf', 'cg': 'google.cg',
'ch': 'google.ch', 'ci': 'google.ci', 'ck': 'google.co.ck',
'cl': 'google.cl', 'cm': 'google.cm', 'cn': 'google.cn',
'co': 'google.com.co', 'cr': 'google.co.cr', 'cu': 'google.com.cu',
'cv': 'google.cv', 'cy': 'google.com.cy', 'cz': 'google.cz',
'de': 'google.de', 'dj': 'google.dj', 'dk': 'google.dk',
'dm': 'google.dm', 'do': 'google.com.do', 'dz': 'google.dz',
'ec': 'google.com.ec', 'ee': 'google.ee', 'eg': 'google.com.eg',
'es': 'google.es', 'et': 'google.com.et', 'fi': 'google.fi',
'fj': 'google.com.fj', 'fm': 'google.fm', 'fr': 'google.fr',
'ga': 'google.ga', 'ge': 'google.ge', 'gf': 'google.gf',
'gg': 'google.gg', 'gh': 'google.com.gh', 'gi': 'google.com.gi',
'gl': 'google.gl', 'gm': 'google.gm', 'gp': 'google.gp',
'gr': 'google.gr', 'gt': 'google.com.gt', 'gy': 'google.gy',
'hk': 'google.com.hk', 'hn': 'google.hn', 'hr': 'google.hr',
'ht': 'google.ht', 'hu': 'google.hu', 'id': 'google.co.id',
'ie': 'google.ie', 'il': 'google.co.il', 'im': 'google.im',
'in': 'google.co.in', 'io': 'google.io', 'iq': 'google.iq',
'is': 'google.is', 'it': 'google.it', 'je': 'google.je',
'jm': 'google.com.jm', 'jo': 'google.jo', 'jp': 'google.co.jp',
'ke': 'google.co.ke', 'kg': 'google.kg', 'kh': 'google.com.kh',
'ki': 'google.ki', 'kr': 'google.co.kr', 'kw': 'google.com.kw',
'kz': 'google.kz', 'la': 'google.la', 'lb': 'google.com.lb',
'lc': 'google.com.lc', 'li': 'google.li', 'lk': 'google.lk',
'ls': 'google.co.ls', 'lt': 'google.lt', 'lu': 'google.lu',
'lv': 'google.lv', 'ly': 'google.com.ly', 'ma': 'google.co.ma',
'md': 'google.md', 'me': 'google.me', 'mg': 'google.mg',
'mk': 'google.mk', 'ml': 'google.ml', 'mm': 'google.com.mm',
'mn': 'google.mn', 'ms': 'google.ms', 'mt': 'google.com.mt',
'mu': 'google.mu', 'mv': 'google.mv', 'mw': 'google.mw',
'mx': 'google.com.mx', 'my': 'google.com.my', 'mz': 'google.co.mz',
'na': 'google.com.na', 'ne': 'google.ne', 'nf': 'google.com.nf',
'ng': 'google.com.ng', 'ni': 'google.com.ni', 'nl': 'google.nl',
'no': 'google.no', 'np': 'google.com.np', 'nr': 'google.nr',
'nu': 'google.nu', 'nz': 'google.co.nz', 'om': 'google.com.om',
'pa': 'google.com.pa', 'pe': 'google.com.pe', 'pg': 'google.com.pg',
'ph': 'google.com.ph', 'pk': 'google.com.pk', 'pl': 'google.pl',
'pn': 'google.co.pn', 'pr': 'google.com.pr', 'ps': 'google.ps',
'pt': 'google.pt', 'py': 'google.com.py', 'qa': 'google.com.qa',
'ro': 'google.ro', 'rs': 'google.rs', 'ru': 'google.ru',
'rw': 'google.rw', 'sa': 'google.com.sa', 'sb': 'google.com.sb',
'sc': 'google.sc', 'se': 'google.se', 'sg': 'google.com.sg',
'sh': 'google.sh', 'si': 'google.si', 'sk': 'google.sk',
'sl': 'google.com.sl', 'sm': 'google.sm', 'sn': 'google.sn',
'so': 'google.so', 'sr': 'google.sr', 'st': 'google.st',
'sv': 'google.com.sv', 'td': 'google.td', 'tg': 'google.tg',
'th': 'google.co.th', 'tj': 'google.com.tj', 'tk': 'google.tk',
'tl': 'google.tl', 'tm': 'google.tm', 'tn': 'google.tn',
'to': 'google.to', 'tr': 'google.com.tr', 'tt': 'google.tt',
'tw': 'google.com.tw', 'tz': 'google.co.tz', 'ua': 'google.com.ua',
'ug': 'google.co.ug', 'uk': 'google.co.uk', 'uy': 'google.com.uy',
'uz': 'google.co.uz', 'vc': 'google.com.vc', 've': 'google.co.ve',
'vg': 'google.vg', 'vi': 'google.co.vi', 'vn': 'google.com.vn',
'vu': 'google.vu', 'ws': 'google.ws', 'za': 'google.co.za',
'zm': 'google.co.zm', 'zw': 'google.co.zw',
}
@property
def netloc(self):
"""The hostname."""
try:
return 'www.' + self.TLD_TO_DOMAIN_MAP[self._tld]
except KeyError:
return 'www.google.com'
@property
def query(self):
"""The query string."""
qd = {}
qd.update(self._query_dict)
qd['num'] = self._num
if self._start:
qd['start'] = self._start
# Construct the q query
q = ''
keywords = self._keywords
if keywords:
if isinstance(keywords, list):
q += '+'.join([urllib.parse.quote_plus(kw) for kw in keywords])
else:
q += urllib.parse.quote_plus(keywords)
if self._site:
q += '+OR'.join(['+site:' + urllib.parse.quote_plus(site) for site in self._site])
qd['q'] = q
return '&'.join(['%s=%s' % (k, qd[k]) for k in sorted(qd.keys())])
class GoogleConnectionError(Exception):
pass
class GoogleConnection(object):
"""
This class facilitates connecting to and fetching from Google.
Parameters
----------
See http.client.HTTPSConnection for documentation of the
parameters.
Raises
------
GoogleConnectionError
Attributes
----------
host : str
The currently connected host. Read-only property. Use
`new_connection` to change host.
Methods
-------
new_connection(host=None, port=None, timeout=45)
renew_connection(timeout=45)
fetch_page(url)
close()
"""
def __init__(self, host, port=None, timeout=45, proxy=None, notweak=False):
self._host = None
self._port = None
self._proxy = proxy
self._notweak = notweak
self._conn = None
self.new_connection(host, port=port, timeout=timeout)
self.cookie = ''
@property
def host(self):
"""The host currently connected to."""
return self._host
def new_connection(self, host=None, port=None, timeout=45):
"""Close the current connection (if any) and establish a new one.
Parameters
----------
See http.client.HTTPSConnection for documentation of the
parameters. Renew the connection (i.e., reuse the current host
and port) if host is None or empty.
Raises
------
GoogleConnectionError
"""
if self._conn:
self._conn.close()
if not host:
host = self._host
port = self._port
self._host = host
self._port = port
host_display = host + (':%d' % port if port else '')
proxy = self._proxy
if proxy:
logger.debug('Connecting to proxy server %s', proxy)
self._conn = TLS1_2Connection(proxy, timeout=timeout)
logger.debug('Tunnelling to host %s' % host_display)
self._conn.set_tunnel(host, port=port)
try:
self._conn.connect(self._notweak)
except Exception as e:
msg = 'Failed to connect to proxy server %s: %s.' % (proxy, e)
raise GoogleConnectionError(msg)
else:
logger.debug('Connecting to new host %s', host_display)
self._conn = TLS1_2Connection(host, port=port, timeout=timeout)
try:
self._conn.connect(self._notweak)
except Exception as e:
msg = 'Failed to connect to %s: %s.' % (host_display, e)
raise GoogleConnectionError(msg)
def renew_connection(self, timeout=45):
"""Renew current connection.
Equivalent to ``new_connection(timeout=timeout)``.
"""
self.new_connection(timeout=timeout)
def fetch_page(self, url):
"""Fetch a URL.
Allows one reconnection and multiple redirections before failing
and raising GoogleConnectionError.
Parameters
----------
url : str
The URL to fetch, relative to the host.
Raises
------
GoogleConnectionError
When not getting HTTP 200 even after the allowed one
reconnection and/or one redirection, or when Google is
blocking query due to unusual activity.
Returns
-------
str
Response payload, gunzipped (if applicable) and decoded (in UTF-8).
"""
try:
self._raw_get(url)
except (http.client.HTTPException, OSError) as e:
logger.debug('Got exception: %s.', e)
logger.debug('Attempting to reconnect...')
self.renew_connection()
try:
self._raw_get(url)
except http.client.HTTPException as e:
logger.debug('Got exception: %s.', e)
raise GoogleConnectionError("Failed to get '%s'." % url)
resp = self._resp
redirect_counter = 0
while resp.status != 200 and redirect_counter < 3:
if resp.status in {301, 302, 303, 307, 308}:
redirection_url = resp.getheader('location', '')
if 'sorry/IndexRedirect?' in redirection_url or 'sorry/index?' in redirection_url:
raise GoogleConnectionError('Connection blocked due to unusual activity.')
self._redirect(redirection_url)
resp = self._resp
redirect_counter += 1
else:
break
if resp.status != 200:
raise GoogleConnectionError('Got HTTP %d: %s' % (resp.status, resp.reason))
payload = resp.read()
try:
return gzip.decompress(payload).decode('utf-8')
except OSError:
# Not gzipped
return payload.decode('utf-8')
def _redirect(self, url):
"""Redirect to and fetch a new URL.
Like `_raw_get`, the response is stored in ``self._resp``. A new
connection is made if redirecting to a different host.
Parameters
----------
url : str
If absolute and points to a different host, make a new
connection.
Raises
------
GoogleConnectionError
"""
logger.debug('Redirecting to URL %s', url)
segments = urllib.parse.urlparse(url)
host = segments.netloc
if host != self._host:
self.new_connection(host)
relurl = urllib.parse.urlunparse(('', '') + segments[2:])
try:
self._raw_get(relurl)
except http.client.HTTPException as e:
logger.debug('Got exception: %s.', e)
raise GoogleConnectionError("Failed to get '%s'." % url)
def _raw_get(self, url):
"""Make a raw HTTP GET request.
No status check (which implies no redirection). Response can be
accessed from ``self._resp``.
Parameters
----------
url : str
URL relative to the host, used in the GET request.
Raises
------
http.client.HTTPException
"""
logger.debug('Fetching URL %s', url)
self._conn.request('GET', url, None, {
'Accept-Encoding': 'gzip',
'User-Agent': USER_AGENT if ua else '',
'Cookie': self.cookie,
'Connection': 'keep-alive',
'DNT': '1',
})
self._resp = self._conn.getresponse()
if self.cookie == '':
complete_cookie = self._resp.getheader('Set-Cookie')
# Cookie won't be available is already blocked
if complete_cookie is not None:
self.cookie = complete_cookie[:complete_cookie.find(';')]
logger.debug('Cookie: %s' % self.cookie)
def close(self):
"""Close the connection (if one is active)."""
if self._conn:
self._conn.close()
def annotate_tag(annotated_starttag_handler):
# See parser logic within the GoogleParser class for documentation.
#
# In particular, search for "Ignore List" to view detailed
# documentation of the ignore list.
#
# annotated_starttag_handler(self, tag: str, attrsdict: dict) -> annotation
# Returns: HTMLParser.handle_starttag(self, tag: str, attrs: list) -> None
def handler(self, tag, attrs):
# Get context; assumes that the handler is called SCOPE_start
context = annotated_starttag_handler.__name__[:-6]
# If context is 'ignore', ignore all tests
if context == 'ignore':
self.insert_annotation(tag, None)
return
attrs = dict(attrs)
# Compare against ignore list
ignored = False
for selector in self.IGNORE_LIST:
for attr in selector:
if attr == 'tag':
if tag != selector['tag']:
break
elif attr == 'class':
tag_classes = set(self.classes(attrs))
selector_classes = set(self.classes(selector))
if not selector_classes.issubset(tag_classes):
break
else:
if attrs[attr] != selector[attr]:
break
else:
# Passed all criteria of the selector
ignored = True
break
# If tag matches ignore list, annotate and hand over to ignore_*
if ignored:
self.insert_annotation(tag, context + '_ignored')
self.set_handlers_to('ignore')
return
# Standard
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 GoogleParser 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 GoogleParser(html.parser.HTMLParser):
"""The members of this class parse the result
HTML page fetched from Google 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 "g".
#
# <!-- within the scope of root_* -->
# <div class="g"> <!-- annotate as 'result', hand over to result_* -->
# </div> <!-- hand back to root_*, register result -->
#
# - For each result, the first <h3> tag with class "r" contains the
# hyperlinked title, and the (optional) first <div> tag with class
# "s" contains the abstract of the result.
#
# <!-- within the scope of result_* -->
# <h3 class="r"> <!-- annotate as 'title', hand over to title_* -->
# </h3> <!-- hand back to result_* -->
# <div class="s"> <!-- annotate as 'abstract', hand over to abstract_* -->
# </div> <!-- hand back to result_* -->
#
# - Each title looks like
#
# <h3 class="r">
# <!-- within the scope of title_* -->
# <span> <!-- filetype (optional), annotate as title_filetype,
# start_populating_textbuf -->
# file type (e.g. [PDF])
# </span> <!-- stop_populating_textbuf -->
# <a href="result url"> <!-- register self.url, annotate as 'title_link',
# start_populating_textbuf -->
# result title
# </a> <!-- stop_populating_textbuf, pop to self.title -->
# </h3>
#