v1ral_ITS

Single Stand Alone Python Terminal Search Googler Script

May 29th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 91.91 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. #
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program.  If not, see <http://www.gnu.org/licenses/>.
  16.  
  17. import argparse
  18. import atexit
  19. import base64
  20. import collections
  21. import codecs
  22. import functools
  23. import gzip
  24. import html.entities
  25. import html.parser
  26. import http.client
  27. from http.client import HTTPSConnection
  28. import locale
  29. import logging
  30. import os
  31. import shutil
  32. import signal
  33. import socket
  34. import ssl
  35. from subprocess import Popen, PIPE, DEVNULL
  36. import sys
  37. import textwrap
  38. import urllib.parse
  39. import webbrowser
  40.  
  41. # Python optional dependency compatibility layer
  42. try:
  43.     import readline
  44. except ImportError:
  45.     pass
  46.  
  47.  
  48. # Basic setup
  49.  
  50. try:
  51.     import setproctitle
  52.     setproctitle.setproctitle('googler')
  53. except Exception:
  54.     pass
  55.  
  56. logging.basicConfig(format='[%(levelname)s] %(message)s')
  57. logger = logging.getLogger()
  58.  
  59.  
  60. def sigint_handler(signum, frame):
  61.     print('\nInterrupted.', file=sys.stderr)
  62.     sys.exit(1)
  63.  
  64. signal.signal(signal.SIGINT, sigint_handler)
  65.  
  66.  
  67. # Constants
  68.  
  69. _VERSION_ = '3.6'
  70.  
  71. COLORMAP = {k: '\x1b[%sm' % v for k, v in {
  72.     'a': '30', 'b': '31', 'c': '32', 'd': '33',
  73.     'e': '34', 'f': '35', 'g': '36', 'h': '37',
  74.     'i': '90', 'j': '91', 'k': '92', 'l': '93',
  75.     'm': '94', 'n': '95', 'o': '96', 'p': '97',
  76.     'A': '30;1', 'B': '31;1', 'C': '32;1', 'D': '33;1',
  77.     'E': '34;1', 'F': '35;1', 'G': '36;1', 'H': '37;1',
  78.     'I': '90;1', 'J': '91;1', 'K': '92;1', 'L': '93;1',
  79.     'M': '94;1', 'N': '95;1', 'O': '96;1', 'P': '97;1',
  80.     'x': '0', 'X': '1', 'y': '7', 'Y': '7;1',
  81. }.items()}
  82.  
  83. # Disguise as Firefox on Ubuntu
  84. USER_AGENT = ('Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:60.0) Gecko/20100101 Firefox/60.0')
  85. ua = True  # User Agent is enabled by default
  86.  
  87. text_browsers = ['elinks', 'links', 'lynx', 'w3m', 'www-browser']
  88.  
  89. # Self-upgrade parameters
  90. #
  91. # Downstream packagers are recommended to turn off the entire self-upgrade
  92. # mechanism through
  93. #
  94. #     make disable-self-upgrade
  95. #
  96. # before running `make install'.
  97.  
  98. ENABLE_SELF_UPGRADE_MECHANISM = True
  99. API_REPO_BASE = 'https://api.github.com/repos/jarun/googler'
  100. RAW_DOWNLOAD_REPO_BASE = 'https://raw.githubusercontent.com/jarun/googler'
  101.  
  102.  
  103. # Global helper functions
  104.  
  105. def open_url(url):
  106.     """Open an URL in the user's default web browser.
  107.  
  108.    The string attribute ``open_url.url_handler`` can be used to open URLs
  109.    in a custom CLI script or utility. A subprocess is spawned with url as
  110.    the parameter in this case instead of the usual webbrowser.open() call.
  111.  
  112.    Whether the browser's output (both stdout and stderr) are suppressed
  113.    depends on the boolean attribute ``open_url.suppress_browser_output``.
  114.    If the attribute is not set upon a call, set it to a default value,
  115.    which means False if BROWSER is set to a known text-based browser --
  116.    elinks, links, lynx, w3m or 'www-browser'; or True otherwise.
  117.  
  118.    The string attribute ``open_url.override_text_browser`` can be used to
  119.    ignore env var BROWSER as well as some known text-based browsers and
  120.    attempt to open url in a GUI browser available.
  121.    Note: If a GUI browser is indeed found, this option ignores the program
  122.          option `show-browser-logs`
  123.    """
  124.     logger.debug('Opening %s', url)
  125.  
  126.     # Custom URL handler gets max priority
  127.     if hasattr(open_url, 'url_handler'):
  128.         p = Popen([open_url.url_handler, url], stdin=PIPE)
  129.         p.communicate()
  130.         return
  131.  
  132.     browser = webbrowser.get()
  133.     if open_url.override_text_browser:
  134.         browser_output = open_url.suppress_browser_output
  135.         for name in [b for b in webbrowser._tryorder if b not in text_browsers]:
  136.             browser = webbrowser.get(name)
  137.             logger.debug(browser)
  138.  
  139.             # Found a GUI browser, suppress browser output
  140.             open_url.suppress_browser_output = True
  141.             break
  142.  
  143.     if open_url.suppress_browser_output:
  144.         _stderr = os.dup(2)
  145.         os.close(2)
  146.         _stdout = os.dup(1)
  147.         os.close(1)
  148.         fd = os.open(os.devnull, os.O_RDWR)
  149.         os.dup2(fd, 2)
  150.         os.dup2(fd, 1)
  151.     try:
  152.         browser.open(url, new=2)
  153.     finally:
  154.         if open_url.suppress_browser_output:
  155.             os.close(fd)
  156.             os.dup2(_stderr, 2)
  157.             os.dup2(_stdout, 1)
  158.  
  159.     if open_url.override_text_browser:
  160.         open_url.suppress_browser_output = browser_output
  161.  
  162.  
  163. def printerr(msg):
  164.     """Print message, verbatim, to stderr.
  165.  
  166.    ``msg`` could be any stringifiable value.
  167.    """
  168.     print(msg, file=sys.stderr)
  169.  
  170.  
  171. def unwrap(text):
  172.     """Unwrap text."""
  173.     lines = text.split('\n')
  174.     result = ''
  175.     for i in range(len(lines) - 1):
  176.         result += lines[i]
  177.         if not lines[i]:
  178.             # Paragraph break
  179.             result += '\n\n'
  180.         elif lines[i + 1]:
  181.             # Next line is not paragraph break, add space
  182.             result += ' '
  183.     # Handle last line
  184.     result += lines[-1] if lines[-1] else '\n'
  185.     return result
  186.  
  187.  
  188. def check_stdout_encoding():
  189.     """Make sure stdout encoding is utf-8.
  190.  
  191.    If not, print error message and instructions, then exit with
  192.    status 1.
  193.  
  194.    This function is a no-op on win32 because encoding on win32 is
  195.    messy, and let's just hope for the best. /s
  196.    """
  197.     if sys.platform == 'win32':
  198.         return
  199.  
  200.     # Use codecs.lookup to resolve text encoding alias
  201.     encoding = codecs.lookup(sys.stdout.encoding).name
  202.     if encoding != 'utf-8':
  203.         locale_lang, locale_encoding = locale.getlocale()
  204.         if locale_lang is None:
  205.             locale_lang = '<unknown>'
  206.         if locale_encoding is None:
  207.             locale_encoding = '<unknown>'
  208.         ioencoding = os.getenv('PYTHONIOENCODING', 'not set')
  209.         sys.stderr.write(unwrap(textwrap.dedent("""\
  210.        stdout encoding '{encoding}' detected. googler requires utf-8 to
  211.        work properly. The wrong encoding may be due to a non-UTF-8
  212.        locale or an improper PYTHONIOENCODING. (For the record, your
  213.        locale language is {locale_lang} and locale encoding is
  214.        {locale_encoding}; your PYTHONIOENCODING is {ioencoding}.)
  215.  
  216.        Please set a UTF-8 locale (e.g., en_US.UTF-8) or set
  217.        PYTHONIOENCODING to utf-8.
  218.        """.format(
  219.             encoding=encoding,
  220.             locale_lang=locale_lang,
  221.             locale_encoding=locale_encoding,
  222.             ioencoding=ioencoding,
  223.         ))))
  224.         sys.exit(1)
  225.  
  226.  
  227. # Classes
  228.  
  229. class TLS1_2Connection(HTTPSConnection):
  230.     """Overrides HTTPSConnection.connect to specify TLS version
  231.  
  232.    NOTE: TLS 1.2 is supported from Python 3.4
  233.    """
  234.  
  235.     def __init__(self, host, **kwargs):
  236.         HTTPSConnection.__init__(self, host, **kwargs)
  237.  
  238.     def connect(self, notweak=False):
  239.         sock = socket.create_connection((self.host, self.port),
  240.                                         self.timeout, self.source_address)
  241.  
  242.         # Optimizations not available on OS X
  243.         if not notweak and sys.platform.startswith('linux'):
  244.             try:
  245.                 sock.setsockopt(socket.SOL_TCP, socket.TCP_DEFER_ACCEPT, 1)
  246.                 sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_QUICKACK, 1)
  247.                 sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 524288)
  248.             except OSError:
  249.                 # Doesn't work on Windows' Linux subsystem (#179)
  250.                 logger.debug('setsockopt failed')
  251.  
  252.         if getattr(self, '_tunnel_host', None):
  253.             self.sock = sock
  254.         elif not notweak:
  255.             # Try to use TLS 1.2
  256.             ssl_context = None
  257.             if hasattr(ssl, 'PROTOCOL_TLS'):
  258.                 # Since Python 3.5.3
  259.                 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLS)
  260.                 ssl_context.options |= (ssl.OP_NO_SSLv2 | ssl.OP_NO_SSLv3 |
  261.                                         ssl.OP_NO_TLSv1 | ssl.OP_NO_TLSv1_1)
  262.             elif hasattr(ssl, 'PROTOCOL_TLSv1_2'):
  263.                 # Since Python 3.4
  264.                 ssl_context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
  265.             if ssl_context:
  266.                 self.sock = ssl_context.wrap_socket(sock)
  267.                 return
  268.  
  269.         # Fallback
  270.         HTTPSConnection.connect(self)
  271.  
  272.  
  273. class GoogleUrl(object):
  274.     """
  275.    This class constructs the Google Search/News URL.
  276.  
  277.    This class is modelled on urllib.parse.ParseResult for familiarity,
  278.    which means it supports reading of all six attributes -- scheme,
  279.    netloc, path, params, query, fragment -- of
  280.    urllib.parse.ParseResult, as well as the geturl() method.
  281.  
  282.    However, the attributes (properties) and methods listed below should
  283.    be the preferred methods of access to this class.
  284.  
  285.    Parameters
  286.    ----------
  287.    opts : dict or argparse.Namespace, optional
  288.        See the ``opts`` parameter of `update`.
  289.  
  290.    Other Parameters
  291.    ----------------
  292.    See "Other Parameters" of `update`.
  293.  
  294.    Attributes
  295.    ----------
  296.    hostname : str
  297.        Read-write property.
  298.    keywords : str or list of strs
  299.        Read-write property.
  300.    news : bool
  301.        Read-only property.
  302.    url : str
  303.        Read-only property.
  304.  
  305.    Methods
  306.    -------
  307.    full()
  308.    relative()
  309.    update(opts=None, **kwargs)
  310.    set_queries(**kwargs)
  311.    unset_queries(*args)
  312.    next_page()
  313.    prev_page()
  314.    first_page()
  315.  
  316.    """
  317.  
  318.     def __init__(self, opts=None, **kwargs):
  319.         self.scheme = 'https'
  320.         # self.netloc is a calculated property
  321.         self.path = '/search'
  322.         self.params = ''
  323.         # self.query is a calculated property
  324.         self.fragment = ''
  325.  
  326.         self._tld = None
  327.         self._num = 10
  328.         self._start = 0
  329.         self._keywords = []
  330.         self._sites = None
  331.         self._query_dict = {
  332.             'ie': 'UTF-8',
  333.             'oe': 'UTF-8',
  334.         }
  335.         self.update(opts, **kwargs)
  336.  
  337.     def __str__(self):
  338.         return self.url
  339.  
  340.     @property
  341.     def url(self):
  342.         """The full Google URL you want."""
  343.         return self.full()
  344.  
  345.     @property
  346.     def hostname(self):
  347.         """The hostname."""
  348.         return self.netloc
  349.  
  350.     @hostname.setter
  351.     def hostname(self, hostname):
  352.         self.netloc = hostname
  353.  
  354.     @property
  355.     def keywords(self):
  356.         """The keywords, either a str or a list of strs."""
  357.         return self._keywords
  358.  
  359.     @keywords.setter
  360.     def keywords(self, keywords):
  361.         self._keywords = keywords
  362.  
  363.     @property
  364.     def news(self):
  365.         """Whether the URL is for Google News."""
  366.         return 'tbm' in self._query_dict and self._query_dict['tbm'] == 'nws'
  367.  
  368.     def full(self):
  369.         """Return the full URL.
  370.  
  371.        Returns
  372.        -------
  373.        str
  374.  
  375.        """
  376.         url = (self.scheme + ':') if self.scheme else ''
  377.         url += '//' + self.netloc + self.relative()
  378.         return url
  379.  
  380.     def relative(self):
  381.         """Return the relative URL (without scheme and authority).
  382.  
  383.        Authority (see RFC 3986 section 3.2), or netloc in the
  384.        terminology of urllib.parse, basically means the hostname
  385.        here. The relative URL is good for making HTTP(S) requests to a
  386.        known host.
  387.  
  388.        Returns
  389.        -------
  390.        str
  391.  
  392.        """
  393.         rel = self.path
  394.         if self.params:
  395.             rel += ';' + self.params
  396.         if self.query:
  397.             rel += '?' + self.query
  398.         if self.fragment:
  399.             rel += '#' + self.fragment
  400.         return rel
  401.  
  402.     def update(self, opts=None, **kwargs):
  403.         """Update the URL with the given options.
  404.  
  405.        Parameters
  406.        ----------
  407.        opts : dict or argparse.Namespace, optional
  408.            Carries options that affect the Google Search/News URL. The
  409.            list of currently recognized option keys with expected value
  410.            types:
  411.  
  412.                duration: str (GooglerArgumentParser.is_duration)
  413.                exact: bool
  414.                keywords: str or list of strs
  415.                lang: str
  416.                news: bool
  417.                num: int
  418.                site: str
  419.                start: int
  420.                tld: str
  421.                unfilter: bool
  422.  
  423.        Other Parameters
  424.        ----------------
  425.        kwargs
  426.            The `kwargs` dict extends `opts`, that is, options can be
  427.            specified either way, in `opts` or as individual keyword
  428.            arguments.
  429.  
  430.        """
  431.  
  432.         if opts is None:
  433.             opts = {}
  434.         if hasattr(opts, '__dict__'):
  435.             opts = opts.__dict__
  436.         opts.update(kwargs)
  437.  
  438.         qd = self._query_dict
  439.         if 'duration' in opts and opts['duration']:
  440.             qd['tbs'] = 'qdr:%s' % opts['duration']
  441.         if 'exact' in opts:
  442.             if opts['exact']:
  443.                 qd['nfpr'] = 1
  444.             else:
  445.                 qd.pop('nfpr', None)
  446.         if 'keywords' in opts:
  447.             self._keywords = opts['keywords']
  448.         if 'lang' in opts and opts['lang']:
  449.             qd['hl'] = opts['lang']
  450.         if 'news' in opts:
  451.             if opts['news']:
  452.                 qd['tbm'] = 'nws'
  453.             else:
  454.                 qd.pop('tbm', None)
  455.         if 'num' in opts:
  456.             self._num = opts['num']
  457.         if 'sites' in opts:
  458.             self._sites = opts['sites']
  459.         if 'start' in opts:
  460.             self._start = opts['start']
  461.         if 'tld' in opts:
  462.             self._tld = opts['tld']
  463.         if 'unfilter' in opts and opts['unfilter']:
  464.             qd['filter'] = 0
  465.  
  466.     def set_queries(self, **kwargs):
  467.         """Forcefully set queries outside the normal `update` mechanism.
  468.  
  469.        Other Parameters
  470.        ----------------
  471.        kwargs
  472.            Arbitrary key value pairs to be set in the query string. All
  473.            keys and values should be stringifiable.
  474.  
  475.            Note that certain keys, e.g., ``q``, have their values
  476.            constructed on the fly, so setting those has no actual
  477.            effect.
  478.  
  479.        """
  480.         for k, v in kwargs.items():
  481.             self._query_dict[k] = v
  482.  
  483.     def unset_queries(self, *args):
  484.         """Forcefully unset queries outside the normal `update` mechanism.
  485.  
  486.        Other Parameters
  487.        ----------------
  488.        args
  489.            Arbitrary keys to be unset. No exception is raised if a key
  490.            does not exist in the first place.
  491.  
  492.            Note that certain keys, e.g., ``q``, are always included in
  493.            the resulting URL, so unsetting those has no actual effect.
  494.  
  495.        """
  496.         for k in args:
  497.             self._query_dict.pop(k, None)
  498.  
  499.     def next_page(self):
  500.         """Navigate to the next page."""
  501.         self._start += self._num
  502.  
  503.     def prev_page(self):
  504.         """Navigate to the previous page.
  505.  
  506.        Raises
  507.        ------
  508.        ValueError
  509.            If already at the first page (``start=0`` in the current
  510.            query string).
  511.  
  512.        """
  513.         if self._start == 0:
  514.             raise ValueError('Already at the first page.')
  515.         self._start = (self._start - self._num) if self._start > self._num else 0
  516.  
  517.     def first_page(self):
  518.         """Navigate to the first page.
  519.  
  520.        Raises
  521.        ------
  522.        ValueError
  523.            If already at the first page (``start=0`` in the current
  524.            query string).
  525.  
  526.        """
  527.         if self._start == 0:
  528.             raise ValueError('Already at the first page.')
  529.         self._start = 0
  530.  
  531.     # Data source: https://web.archive.org/web/20170615200243/https://en.wikipedia.org/wiki/List_of_Google_domains
  532.     # Scraper script: https://gist.github.com/zmwangx/b976e83c14552fe18b71
  533.     TLD_TO_DOMAIN_MAP = {
  534.         'ac': 'google.ac',      'ad': 'google.ad',      'ae': 'google.ae',
  535.         'af': 'google.com.af',  'ag': 'google.com.ag',  'ai': 'google.com.ai',
  536.         'al': 'google.al',      'am': 'google.am',      'ao': 'google.co.ao',
  537.         'ar': 'google.com.ar',  'as': 'google.as',      'at': 'google.at',
  538.         'au': 'google.com.au',  'az': 'google.az',      'ba': 'google.ba',
  539.         'bd': 'google.com.bd',  'be': 'google.be',      'bf': 'google.bf',
  540.         'bg': 'google.bg',      'bh': 'google.com.bh',  'bi': 'google.bi',
  541.         'bj': 'google.bj',      'bn': 'google.com.bn',  'bo': 'google.com.bo',
  542.         'br': 'google.com.br',  'bs': 'google.bs',      'bt': 'google.bt',
  543.         'bw': 'google.co.bw',   'by': 'google.by',      'bz': 'google.com.bz',
  544.         'ca': 'google.ca',      'cat': 'google.cat',    'cc': 'google.cc',
  545.         'cd': 'google.cd',      'cf': 'google.cf',      'cg': 'google.cg',
  546.         'ch': 'google.ch',      'ci': 'google.ci',      'ck': 'google.co.ck',
  547.         'cl': 'google.cl',      'cm': 'google.cm',      'cn': 'google.cn',
  548.         'co': 'google.com.co',  'cr': 'google.co.cr',   'cu': 'google.com.cu',
  549.         'cv': 'google.cv',      'cy': 'google.com.cy',  'cz': 'google.cz',
  550.         'de': 'google.de',      'dj': 'google.dj',      'dk': 'google.dk',
  551.         'dm': 'google.dm',      'do': 'google.com.do',  'dz': 'google.dz',
  552.         'ec': 'google.com.ec',  'ee': 'google.ee',      'eg': 'google.com.eg',
  553.         'es': 'google.es',      'et': 'google.com.et',  'fi': 'google.fi',
  554.         'fj': 'google.com.fj',  'fm': 'google.fm',      'fr': 'google.fr',
  555.         'ga': 'google.ga',      'ge': 'google.ge',      'gf': 'google.gf',
  556.         'gg': 'google.gg',      'gh': 'google.com.gh',  'gi': 'google.com.gi',
  557.         'gl': 'google.gl',      'gm': 'google.gm',      'gp': 'google.gp',
  558.         'gr': 'google.gr',      'gt': 'google.com.gt',  'gy': 'google.gy',
  559.         'hk': 'google.com.hk',  'hn': 'google.hn',      'hr': 'google.hr',
  560.         'ht': 'google.ht',      'hu': 'google.hu',      'id': 'google.co.id',
  561.         'ie': 'google.ie',      'il': 'google.co.il',   'im': 'google.im',
  562.         'in': 'google.co.in',   'io': 'google.io',      'iq': 'google.iq',
  563.         'is': 'google.is',      'it': 'google.it',      'je': 'google.je',
  564.         'jm': 'google.com.jm',  'jo': 'google.jo',      'jp': 'google.co.jp',
  565.         'ke': 'google.co.ke',   'kg': 'google.kg',      'kh': 'google.com.kh',
  566.         'ki': 'google.ki',      'kr': 'google.co.kr',   'kw': 'google.com.kw',
  567.         'kz': 'google.kz',      'la': 'google.la',      'lb': 'google.com.lb',
  568.         'lc': 'google.com.lc',  'li': 'google.li',      'lk': 'google.lk',
  569.         'ls': 'google.co.ls',   'lt': 'google.lt',      'lu': 'google.lu',
  570.         'lv': 'google.lv',      'ly': 'google.com.ly',  'ma': 'google.co.ma',
  571.         'md': 'google.md',      'me': 'google.me',      'mg': 'google.mg',
  572.         'mk': 'google.mk',      'ml': 'google.ml',      'mm': 'google.com.mm',
  573.         'mn': 'google.mn',      'ms': 'google.ms',      'mt': 'google.com.mt',
  574.         'mu': 'google.mu',      'mv': 'google.mv',      'mw': 'google.mw',
  575.         'mx': 'google.com.mx',  'my': 'google.com.my',  'mz': 'google.co.mz',
  576.         'na': 'google.com.na',  'ne': 'google.ne',      'nf': 'google.com.nf',
  577.         'ng': 'google.com.ng',  'ni': 'google.com.ni',  'nl': 'google.nl',
  578.         'no': 'google.no',      'np': 'google.com.np',  'nr': 'google.nr',
  579.         'nu': 'google.nu',      'nz': 'google.co.nz',   'om': 'google.com.om',
  580.         'pa': 'google.com.pa',  'pe': 'google.com.pe',  'pg': 'google.com.pg',
  581.         'ph': 'google.com.ph',  'pk': 'google.com.pk',  'pl': 'google.pl',
  582.         'pn': 'google.co.pn',   'pr': 'google.com.pr',  'ps': 'google.ps',
  583.         'pt': 'google.pt',      'py': 'google.com.py',  'qa': 'google.com.qa',
  584.         'ro': 'google.ro',      'rs': 'google.rs',      'ru': 'google.ru',
  585.         'rw': 'google.rw',      'sa': 'google.com.sa',  'sb': 'google.com.sb',
  586.         'sc': 'google.sc',      'se': 'google.se',      'sg': 'google.com.sg',
  587.         'sh': 'google.sh',      'si': 'google.si',      'sk': 'google.sk',
  588.         'sl': 'google.com.sl',  'sm': 'google.sm',      'sn': 'google.sn',
  589.         'so': 'google.so',      'sr': 'google.sr',      'st': 'google.st',
  590.         'sv': 'google.com.sv',  'td': 'google.td',      'tg': 'google.tg',
  591.         'th': 'google.co.th',   'tj': 'google.com.tj',  'tk': 'google.tk',
  592.         'tl': 'google.tl',      'tm': 'google.tm',      'tn': 'google.tn',
  593.         'to': 'google.to',      'tr': 'google.com.tr',  'tt': 'google.tt',
  594.         'tw': 'google.com.tw',  'tz': 'google.co.tz',   'ua': 'google.com.ua',
  595.         'ug': 'google.co.ug',   'uk': 'google.co.uk',   'uy': 'google.com.uy',
  596.         'uz': 'google.co.uz',   'vc': 'google.com.vc',  've': 'google.co.ve',
  597.         'vg': 'google.vg',      'vi': 'google.co.vi',   'vn': 'google.com.vn',
  598.         'vu': 'google.vu',      'ws': 'google.ws',      'za': 'google.co.za',
  599.         'zm': 'google.co.zm',   'zw': 'google.co.zw',
  600.     }
  601.  
  602.     @property
  603.     def netloc(self):
  604.         """The hostname."""
  605.         try:
  606.             return 'www.' + self.TLD_TO_DOMAIN_MAP[self._tld]
  607.         except KeyError:
  608.             return 'www.google.com'
  609.  
  610.     @property
  611.     def query(self):
  612.         """The query string."""
  613.         qd = {}
  614.         qd.update(self._query_dict)
  615.         if self._num != 10:  # Skip sending the default
  616.             qd['num'] = self._num
  617.         if self._start:  # Skip sending the default
  618.             qd['start'] = self._start
  619.  
  620.         # Construct the q query
  621.         q = ''
  622.         keywords = self._keywords
  623.         sites = self._sites
  624.         if keywords:
  625.             if isinstance(keywords, list):
  626.                 q += '+'.join(urllib.parse.quote_plus(kw) for kw in keywords)
  627.             else:
  628.                 q += urllib.parse.quote_plus(keywords)
  629.         if sites:
  630.             q += '+OR'.join('+site:' + urllib.parse.quote_plus(site) for site in sites)
  631.         qd['q'] = q
  632.  
  633.         return '&'.join('%s=%s' % (k, qd[k]) for k in sorted(qd.keys()))
  634.  
  635.  
  636. class GoogleConnectionError(Exception):
  637.     pass
  638.  
  639.  
  640. class GoogleConnection(object):
  641.     """
  642.    This class facilitates connecting to and fetching from Google.
  643.  
  644.    Parameters
  645.    ----------
  646.    See http.client.HTTPSConnection for documentation of the
  647.    parameters.
  648.  
  649.    Raises
  650.    ------
  651.    GoogleConnectionError
  652.  
  653.    Attributes
  654.    ----------
  655.    host : str
  656.        The currently connected host. Read-only property. Use
  657.        `new_connection` to change host.
  658.  
  659.    Methods
  660.    -------
  661.    new_connection(host=None, port=None, timeout=45)
  662.    renew_connection(timeout=45)
  663.    fetch_page(url)
  664.    close()
  665.  
  666.    """
  667.  
  668.     def __init__(self, host, port=None, timeout=45, proxy=None, notweak=False):
  669.         self._host = None
  670.         self._port = None
  671.         self._proxy = proxy
  672.         self._notweak = notweak
  673.         self._conn = None
  674.         self.new_connection(host, port=port, timeout=timeout)
  675.         self.cookie = ''
  676.  
  677.     @property
  678.     def host(self):
  679.         """The host currently connected to."""
  680.         return self._host
  681.  
  682.     def new_connection(self, host=None, port=None, timeout=45):
  683.         """Close the current connection (if any) and establish a new one.
  684.  
  685.        Parameters
  686.        ----------
  687.        See http.client.HTTPSConnection for documentation of the
  688.        parameters. Renew the connection (i.e., reuse the current host
  689.        and port) if host is None or empty.
  690.  
  691.        Raises
  692.        ------
  693.        GoogleConnectionError
  694.  
  695.        """
  696.         if self._conn:
  697.             self._conn.close()
  698.  
  699.         if not host:
  700.             host = self._host
  701.             port = self._port
  702.         self._host = host
  703.         self._port = port
  704.         host_display = host + (':%d' % port if port else '')
  705.  
  706.         proxy = self._proxy
  707.  
  708.         if proxy:
  709.             proxy_user_passwd, proxy_host_port = parse_proxy_spec(proxy)
  710.  
  711.             logger.debug('Connecting to proxy server %s', proxy_host_port)
  712.             self._conn = TLS1_2Connection(proxy_host_port, timeout=timeout)
  713.  
  714.             logger.debug('Tunnelling to host %s' % host_display)
  715.             connect_headers = {}
  716.             if proxy_user_passwd:
  717.                 connect_headers['Proxy-Authorization'] = 'Basic %s' % base64.b64encode(
  718.                     proxy_user_passwd.encode('utf-8')
  719.                 ).decode('utf-8')
  720.             self._conn.set_tunnel(host, port=port, headers=connect_headers)
  721.  
  722.             try:
  723.                 self._conn.connect(self._notweak)
  724.             except Exception as e:
  725.                 msg = 'Failed to connect to proxy server %s: %s.' % (proxy, e)
  726.                 raise GoogleConnectionError(msg)
  727.         else:
  728.             logger.debug('Connecting to new host %s', host_display)
  729.             self._conn = TLS1_2Connection(host, port=port, timeout=timeout)
  730.             try:
  731.                 self._conn.connect(self._notweak)
  732.             except Exception as e:
  733.                 msg = 'Failed to connect to %s: %s.' % (host_display, e)
  734.                 raise GoogleConnectionError(msg)
  735.  
  736.     def renew_connection(self, timeout=45):
  737.         """Renew current connection.
  738.  
  739.        Equivalent to ``new_connection(timeout=timeout)``.
  740.  
  741.        """
  742.         self.new_connection(timeout=timeout)
  743.  
  744.     def fetch_page(self, url):
  745.         """Fetch a URL.
  746.  
  747.        Allows one reconnection and multiple redirections before failing
  748.        and raising GoogleConnectionError.
  749.  
  750.        Parameters
  751.        ----------
  752.        url : str
  753.            The URL to fetch, relative to the host.
  754.  
  755.        Raises
  756.        ------
  757.        GoogleConnectionError
  758.            When not getting HTTP 200 even after the allowed one
  759.            reconnection and/or one redirection, or when Google is
  760.            blocking query due to unusual activity.
  761.  
  762.        Returns
  763.        -------
  764.        str
  765.            Response payload, gunzipped (if applicable) and decoded (in UTF-8).
  766.  
  767.        """
  768.         try:
  769.             self._raw_get(url)
  770.         except (http.client.HTTPException, OSError) as e:
  771.             logger.debug('Got exception: %s.', e)
  772.             logger.debug('Attempting to reconnect...')
  773.             self.renew_connection()
  774.             try:
  775.                 self._raw_get(url)
  776.             except http.client.HTTPException as e:
  777.                 logger.debug('Got exception: %s.', e)
  778.                 raise GoogleConnectionError("Failed to get '%s'." % url)
  779.  
  780.         resp = self._resp
  781.         redirect_counter = 0
  782.         while resp.status != 200 and redirect_counter < 3:
  783.             if resp.status in {301, 302, 303, 307, 308}:
  784.                 redirection_url = resp.getheader('location', '')
  785.                 if 'sorry/IndexRedirect?' in redirection_url or 'sorry/index?' in redirection_url:
  786.                     raise GoogleConnectionError('Connection blocked due to unusual activity.')
  787.                 self._redirect(redirection_url)
  788.                 resp = self._resp
  789.                 redirect_counter += 1
  790.             else:
  791.                 break
  792.  
  793.         if resp.status != 200:
  794.             raise GoogleConnectionError('Got HTTP %d: %s' % (resp.status, resp.reason))
  795.  
  796.         payload = resp.read()
  797.         try:
  798.             return gzip.decompress(payload).decode('utf-8')
  799.         except OSError:
  800.             # Not gzipped
  801.             return payload.decode('utf-8')
  802.  
  803.     def _redirect(self, url):
  804.         """Redirect to and fetch a new URL.
  805.  
  806.        Like `_raw_get`, the response is stored in ``self._resp``. A new
  807.        connection is made if redirecting to a different host.
  808.  
  809.        Parameters
  810.        ----------
  811.        url : str
  812.            If absolute and points to a different host, make a new
  813.            connection.
  814.  
  815.        Raises
  816.        ------
  817.        GoogleConnectionError
  818.  
  819.        """
  820.         logger.debug('Redirecting to URL %s', url)
  821.         segments = urllib.parse.urlparse(url)
  822.  
  823.         host = segments.netloc
  824.         if host != self._host:
  825.             self.new_connection(host)
  826.  
  827.         relurl = urllib.parse.urlunparse(('', '') + segments[2:])
  828.         try:
  829.             self._raw_get(relurl)
  830.         except http.client.HTTPException as e:
  831.             logger.debug('Got exception: %s.', e)
  832.             raise GoogleConnectionError("Failed to get '%s'." % url)
  833.  
  834.     def _raw_get(self, url):
  835.         """Make a raw HTTP GET request.
  836.  
  837.        No status check (which implies no redirection). Response can be
  838.        accessed from ``self._resp``.
  839.  
  840.        Parameters
  841.        ----------
  842.        url : str
  843.            URL relative to the host, used in the GET request.
  844.  
  845.        Raises
  846.        ------
  847.        http.client.HTTPException
  848.  
  849.        """
  850.         logger.debug('Fetching URL %s', url)
  851.         self._conn.request('GET', url, None, {
  852.             'Accept-Encoding': 'gzip',
  853.             'User-Agent': USER_AGENT if ua else '',
  854.             'Cookie': self.cookie,
  855.             'Connection': 'keep-alive',
  856.             'DNT': '1',
  857.         })
  858.         self._resp = self._conn.getresponse()
  859.         if self.cookie == '':
  860.             complete_cookie = self._resp.getheader('Set-Cookie')
  861.             # Cookie won't be available is already blocked
  862.             if complete_cookie is not None:
  863.                 self.cookie = complete_cookie[:complete_cookie.find(';')]
  864.                 logger.debug('Cookie: %s' % self.cookie)
  865.  
  866.     def close(self):
  867.         """Close the connection (if one is active)."""
  868.         if self._conn:
  869.             self._conn.close()
  870.  
  871.  
  872. def annotate_tag(annotated_starttag_handler):
  873.     # See parser logic within the GoogleParser class for documentation.
  874.     #
  875.     # In particular, search for "Ignore List" to view detailed
  876.     # documentation of the ignore list.
  877.     #
  878.     # annotated_starttag_handler(self, tag: str, attrsdict: dict) -> annotation
  879.     # Returns: HTMLParser.handle_starttag(self, tag: str, attrs: list) -> None
  880.  
  881.     def handler(self, tag, attrs):
  882.         # Get context; assumes that the handler is called SCOPE_start
  883.         context = annotated_starttag_handler.__name__[:-6]
  884.  
  885.         # If context is 'ignore', ignore all tests
  886.         if context == 'ignore':
  887.             self.insert_annotation(tag, None)
  888.             return
  889.  
  890.         attrs = dict(attrs)
  891.  
  892.         # Compare against ignore list
  893.         ignored = False
  894.         for selector in self.IGNORE_LIST:
  895.             for attr in selector:
  896.                 if attr == 'tag':
  897.                     if tag != selector['tag']:
  898.                         break
  899.                 elif attr == 'class':
  900.                     tag_classes = set(self.classes(attrs))
  901.                     selector_classes = set(self.classes(selector))
  902.                     if not selector_classes.issubset(tag_classes):
  903.                         break
  904.                 else:
  905.                     if attrs[attr] != selector[attr]:
  906.                         break
  907.             else:
  908.                 # Passed all criteria of the selector
  909.                 ignored = True
  910.                 break
  911.  
  912.         # If tag matches ignore list, annotate and hand over to ignore_*
  913.         if ignored:
  914.             self.insert_annotation(tag, context + '_ignored')
  915.             self.set_handlers_to('ignore')
  916.             return
  917.  
  918.         # Standard
  919.         annotation = annotated_starttag_handler(self, tag, attrs)
  920.         self.insert_annotation(tag, annotation)
  921.  
  922.     return handler
  923.  
  924.  
  925. def retrieve_tag_annotation(annotated_endtag_handler):
  926.     # See parser logic within the GoogleParser class for documentation.
  927.     #
  928.     # annotated_endtag_handler(self, tag: str, annotation) -> None
  929.     # Returns: HTMLParser.handle_endtag(self, tag: str) -> None
  930.  
  931.     def handler(self, tag):
  932.         try:
  933.             annotation = self.tag_annotations[tag].pop()
  934.         except IndexError:
  935.             # Malformed HTML -- more close tags than open tags
  936.             annotation = None
  937.         annotated_endtag_handler(self, tag, annotation)
  938.  
  939.     return handler
  940.  
  941.  
  942. class GoogleParser(html.parser.HTMLParser):
  943.     """The members of this class parse the result
  944.    HTML page fetched from Google server for a query.
  945.  
  946.    The custom parser looks for tags enclosing search
  947.    results and extracts the URL, title and text for
  948.    each search result.
  949.  
  950.    After parsing the complete HTML page results are
  951.    returned in a list of objects of class Result.
  952.    """
  953.  
  954.     # Parser logic:
  955.     #
  956.     # - Guiding principles:
  957.     #
  958.     #   1. Tag handlers are contextual;
  959.     #
  960.     #   2. Contextual starttag and endtag handlers should come in pairs
  961.     #      and have a clear hierarchy;
  962.     #
  963.     #   3. starttag handlers should only yield control to a pair of
  964.     #      child handlers (that is, one level down the hierarchy), and
  965.     #      correspondingly, endtag handlers should only return control
  966.     #      to the parent (that is, the pair of handlers that gave it
  967.     #      control in the first place).
  968.     #
  969.     #   Principle 3 is meant to enforce a (possibly implicit) stack
  970.     #   structure and thus prevent careless jumps that result in what's
  971.     #   essentially spaghetti code with liberal use of GOTOs.
  972.     #
  973.     # - HTMLParser.handle_endtag gives us a bare tag name without
  974.     #   context, which is not good for enforcing principle 3 when we
  975.     #   have, say, nested div tags.
  976.     #
  977.     #   In order to precisely identify the matching opening tag, we
  978.     #   maintain a stack for each tag name with *annotations*. Important
  979.     #   opening tags (e.g., the ones where child handlers are
  980.     #   registered) can be annotated so that when we can watch for the
  981.     #   annotation in the endtag handler, and when the appropriate
  982.     #   annotation is popped, we perform the corresponding action (e.g.,
  983.     #   switch back to old handlers).
  984.     #
  985.     #   To facilitate this, each starttag handler is decorated with
  986.     #   @annotate_tag, which accepts a return value that is the
  987.     #   annotation (None by default), and additionally converts attrs to
  988.     #   a dict, which is much easier to work with; and each endtag
  989.     #   handler is decorated with @retrieve_tag_annotation which sends
  990.     #   an additional parameter that is the retrieved annotation to the
  991.     #   handler.
  992.     #
  993.     #   Note that some of our tag annotation stacks leak over time: this
  994.     #   happens to tags like <img> and <hr> which are not
  995.     #   closed. However, these tags play no structural role, and come
  996.     #   only in small quantities, so it's not really a problem.
  997.     #
  998.     # - All textual data (result title, result abstract, etc.) are
  999.     #   processed through a set of shared handlers. These handlers store
  1000.     #   text in a shared buffer self.textbuf which can be retrieved and
  1001.     #   cleared at appropriate times.
  1002.     #
  1003.     #   Data (including charrefs and entityrefs) are ignored initially,
  1004.     #   and when data needs to be recorded, the start_populating_textbuf
  1005.     #   method is called to register the appropriate data, charref and
  1006.     #   entityref handlers so that they append to self.textbuf. When
  1007.     #   recording ends, pop_textbuf should be called to extract the text
  1008.     #   and clear the buffer. stop_populating_textbuf returns the
  1009.     #   handlers to their pristine state (ignoring data).
  1010.     #
  1011.     #   Methods:
  1012.     #   - start_populating_textbuf(self, data_transformer: Callable[[str], str]) -> None
  1013.     #   - pop_textbuf(self) -> str
  1014.     #   - stop_populating_textbuf(self) -> None
  1015.     #
  1016.     # - Outermost starttag and endtag handler methods: root_*. The whole
  1017.     #   parser starts and ends in this state.
  1018.     #
  1019.     # - Each result is wrapped in a <div> tag with class "g".
  1020.     #
  1021.     #   <!-- within the scope of root_* -->
  1022.     #   <div class="g">  <!-- annotate as 'result', hand over to result_* -->
  1023.     #   </div>           <!-- hand back to root_*, register result -->
  1024.     #
  1025.     # - For each result, the first <h3> tag with class "r" contains the
  1026.     #   hyperlinked title, and the (optional) first <div> tag with class
  1027.     #   "s" contains the abstract of the result.
  1028.     #
  1029.     #   <!-- within the scope of result_* -->
  1030.     #   <h3 class="r">   <!-- annotate as 'title', hand over to title_* -->
  1031.     #   </h3>            <!-- hand back to result_* -->
  1032.     #   <div class="s">  <!-- annotate as 'abstract', hand over to abstract_* -->
  1033.     #   </div>           <!-- hand back to result_* -->
  1034.     #
  1035.     # - Each title looks like
  1036.     #
  1037.     #   <h3 class="r">
  1038.     #     <!-- within the scope of title_* -->
  1039.     #     <span>                 <!-- filetype (optional), annotate as title_filetype,
  1040.     #                                 start_populating_textbuf -->
  1041.     #       file type (e.g. [PDF])
  1042.     #     </span>                <!-- stop_populating_textbuf -->
  1043.     #     <a href="result url">  <!-- register self.url, annotate as 'title_link',
  1044.     #                                 start_populating_textbuf -->
  1045.     #       result title
  1046.     #     </a>                   <!-- stop_populating_textbuf, pop to self.title -->
  1047.     #   </h3>
  1048.     #
  1049.     # - For each abstract, the first <span> tag with class "st" contains
  1050.     #   the body text of the abstract.
  1051.     #
  1052.     #   <!-- within the scope of abstract_* -->
  1053.     #   <span class="st">  <!-- annotate as 'abstract_text', start_populating_textbuf -->
  1054.     #     abstract text with <em> markup on keywords
  1055.     #   </span>            <!-- stop_populating_textbuf, pop to self.abstract -->
  1056.     #
  1057.     # - Certain results may come with sitelinks, secondary results that
  1058.     #   are usually subdomains or deep links within the primary
  1059.     #   result. They are organized into a <table> tag, and each sitelink
  1060.     #   is in a separate <td>:
  1061.     #
  1062.     #   <!-- within the scope of result_* -->
  1063.     #   <table>    <!-- annotate as 'sitelink_table', hand over to sitelink_table_* -->
  1064.     #     <tr>
  1065.     #       <td>   <!-- annotate as 'sitelink', hand over to sitelink_* -->
  1066.     #       </td>  <!-- append to self.sitelinks, hand back to sitelink_table_* -->
  1067.     #       <td></td>
  1068.     #       ...
  1069.     #     </tr>
  1070.     #     <tr></tr>
  1071.     #     ...
  1072.     #   </table>   <!-- hand back to result_* -->
  1073.     #
  1074.     #   Then for each sitelink, the hyperlinked title is in an <h3> tag
  1075.     #   with class "r", and the abstract is in a <div> tag with class
  1076.     #   "st". They are not necessarily on the same level, but we don't
  1077.     #   really care.
  1078.     #
  1079.     #   <!-- within the scope of sitelink_* -->
  1080.     #   <h3 class="r">             <!-- annotate as 'sitelink_title',
  1081.     #                                   hand over to sitelink_title_* -->
  1082.     #     <a href="sitelink url">  <!-- register sitelink url, annotate as 'sitelink_title_link',
  1083.     #                                   start_populating_textbuf -->
  1084.     #       sitelink title
  1085.     #     </a>                     <!-- stop_populating_textbuf, pop to sitelink title -->
  1086.     #   </h3>                      <!-- hand back to sitelink_* -->
  1087.     #
  1088.     #   <!-- still within the scope of sitelink_* -->
  1089.     #   <div class="st">  <!-- annotate as 'sitelink_abstract', start_populating_textbuf -->
  1090.     #     abstract text
  1091.     #   </div>            <!-- stop_populating_textbuf, pop to sitelink abstract -->
  1092.     #
  1093.     # - Sometimes Google autocorrects a query. Whenever this happens
  1094.     #   there will be a block whose English version reads "Showing
  1095.     #   results for ... <newline> Search instead for ...", and the HTML
  1096.     #   looks like
  1097.     #
  1098.     #   <span class="spell">Showing results for</span>
  1099.     #   <a class="spell" href="/search?q=google..."><b><i>google</i></b></a>
  1100.     #   <br>
  1101.     #   <span class="spell_orig"></span>
  1102.     #
  1103.     #   We collect the text inside a.spell as the suggested spelling
  1104.     #   (self.suggested_spelling).
  1105.     #
  1106.     #   Note that:
  1107.     #
  1108.     #   1. When npfr=1 (exact), there could still be an
  1109.     #      a.spell, in a block that reads (English version) "Did you mean:
  1110.     #      ...". Therefore, we only consider the query autocorrected when a
  1111.     #      meaningful .spell_orig is also present (self.autocorrected).
  1112.     #
  1113.     #   2. A few garbage display:none, empty tags related to spell
  1114.     #      appear to be always present: span#srfm.spell, a#srfl.spell,
  1115.     #      span#sifm.spell_orig, a#sifl.spell_orig. We need to exclude
  1116.     #      the ids srfm, srfl, sifm and sifl from our consideration.
  1117.     #
  1118.     # - Sometimes Google omits similar (more like duplicate) result
  1119.     #   entries. Whenever this happens there will be a notice in p#ofr. The way
  1120.     #   to unfilter is to simply add '&filter=0' to the query string.
  1121.     #
  1122.     #
  1123.     # Google News
  1124.     #
  1125.     # - Google News results differ from Google Search results in the
  1126.     #   following ways:
  1127.     #
  1128.     #   For each result, the title in the same format, but there's a
  1129.     #   metadata field in a <div> tag with class "slp", and the abstract
  1130.     #   isn't as deeply embedded: it's in a <div> tag on the same level
  1131.     #   with class "st".
  1132.     #
  1133.     #   <!-- within the scope of result_* -->
  1134.     #   <h3 class="r"></h3>  <!-- as before -->
  1135.     #   <div class="slp">    <!-- annotate as 'news_metadata', start_populating_textbuf -->
  1136.     #     ...
  1137.     #     <span>source</span>
  1138.     #     <span>-</span>     <!-- transform to ', ' -->
  1139.     #     <span>publishing time</span>
  1140.     #   </div>               <!-- stop_populating_textbuf, pop to self.metadata -->
  1141.     #   <div class="st">     <!-- annotate as 'news_abstract', start_populating_textbuf -->
  1142.     #     abstract text again with <em> markup on keywords
  1143.     #   </div>               <!-- stop_populating_textbuf, pop to self.abstract -->
  1144.     #
  1145.     #
  1146.     # Ignore List
  1147.     #
  1148.     # - As good as our result criteria might be, sometimes results of
  1149.     #   dubious value (usually from Google's value-add features) slip
  1150.     #   through. The "People also ask" feature is a good example of this
  1151.     #   type (a sample query is "VPN"; see screenshot
  1152.     #   https://i.imgur.com/yfcsoQz.png). In these cases, we may want to
  1153.     #   skip enclosing containers entirely. The ignore list feature is
  1154.     #   designed for this purpose.
  1155.     #
  1156.     #   The current ignore list is available in self.IGNORE_LIST. Each
  1157.     #   entry (called a "selector") is a dict of attribute-value
  1158.     #   pairs. Each attribute is matched verbatim to a tag's attribute,
  1159.     #   except the "class" attribute, where we test for inclusion
  1160.     #   instead (e.g. "c b a" matches "a b", just like it matches the
  1161.     #   CSS selector ".a.b"). There's also a special "attribute" -- tag,
  1162.     #   the meaning of which is obvious. A tag has to match all given
  1163.     #   attributes to be considered a match for the selector.
  1164.     #
  1165.     #   When a match is found, the tag is annotated as SCOPE_ignored,
  1166.     #   where SCOPE is the current handler scope (e.g., root, result,
  1167.     #   title, etc.), and the scope is switched to 'ignore'. All
  1168.     #   descendants of the tag are ignored. When the corresponding end
  1169.     #   tag is finally reach, the former scope is restored.
  1170.     #
  1171.     #
  1172.     # User Agent disabled (differences)
  1173.     #
  1174.     #   1. For Google News results, <div class="g"> is followed by <table> tag
  1175.     #       <div class="g">
  1176.     #           <table>
  1177.     #
  1178.     #   2. File mime type follows <div class="g">
  1179.     #       <div class="g"><span style="float:left"><span class="mime">[PDF]</span>&nbsp;</span>
  1180.     #
  1181.     #   3. News metadata (source and time) comes within a single tag
  1182.     #       <div class="slp"><span class="f">Reuters - 3 hours ago</span>
  1183.     #
  1184.     #   4. URLs are wrapped
  1185.     #       <a href="/url?q=http://...&sa=...">
  1186.     #
  1187.     #   5. URLs are quoted
  1188.     #       'https://vk.com/doc206446660_429188746%3Fhash%3D6097a8b0a41185cb90%26dl%3D03c63c1be5c02e8620'
  1189.     #
  1190.     #   6. Google Services links are returned as regular results,
  1191.     #      start with '/search?q=' but no following 'http' or 'https'
  1192.     #       <div class="g">
  1193.     #           <div>
  1194.     #               <h3 class="r"><a href="/search?q=india&...&sa=...">News for <b>india</b></a></h3>
  1195.     #
  1196.     #   7. YouTube specific results are returned within <table class="ts">
  1197.     #       e.g. search - '3 hours youtube'
  1198.     #
  1199.     #       <span class="st">
  1200.     #           <span class="f"><span class="nobr">10 Jun 2014</span> - <span class="nobr">179 min</span> -
  1201.     #               <span class="nobr">Uploaded by Meditation Relax Music</span>
  1202.     #           </span>
  1203.     #           <br><b>3 HOURS Best Relaxing Music</b> &#39;Romantic <b>Piano</b>&quot; Background <b>Music</b> for Stress ... 3:03 <b>...</b>
  1204.     #       </span>
  1205.     #
  1206.     #   8. There's no a.spell_orig when the query is autocorrected; the
  1207.     #      <a> tag (linking to the exact search) is wrapped in the
  1208.     #      span.spell_orig.
  1209.  
  1210.     def __init__(self, news=False):
  1211.         html.parser.HTMLParser.__init__(self)
  1212.  
  1213.         self.news = news
  1214.  
  1215.         self.autocorrected = False
  1216.         self.suggested_spelling = None
  1217.         self.filtered = False
  1218.         self.results = []
  1219.  
  1220.         self.index = 0
  1221.         self.textbuf = ''
  1222.         self.tag_annotations = {}
  1223.  
  1224.         self.set_handlers_to('root')
  1225.  
  1226.     # Ignore list
  1227.     IGNORE_LIST = [
  1228.         # "People also ask"
  1229.         # Sample query: VPN
  1230.         # Screenshot: https://i.imgur.com/yfcsoQz.png
  1231.         {
  1232.             'tag': 'div',
  1233.             'class': 'related-question-pair'
  1234.         },
  1235.         # We omit Google's "smart card" results (term coined by me) by
  1236.         # guarding against the 'g-blk' class (sample response: https://git.io/voJgB)
  1237.         {
  1238.             'tag': 'div',
  1239.             'class': 'g-blk'
  1240.         },
  1241.         # We also guard against "smart-card" results with `--noua` option
  1242.         {
  1243.             'tag': 'div',
  1244.             'class': 'hp-xpdbox'
  1245.         }
  1246.     ]
  1247.  
  1248.     # Tag handlers
  1249.  
  1250.     @annotate_tag
  1251.     def root_start(self, tag, attrs):
  1252.         if tag == 'div' and 'g' in self.classes(attrs):
  1253.             # Initialize result field registers
  1254.             self.title = ''
  1255.             self.url = ''
  1256.             self.abstract = ''
  1257.             self.metadata = ''  # Only used for Google News
  1258.             self.sitelinks = []
  1259.  
  1260.             # Guard against sitelinks, which also have titles and
  1261.             # abstracts.  In the case of news, guard against "card
  1262.             # sections" (secondary results to the same event).
  1263.             self.title_registered = False
  1264.             self.abstract_registered = False
  1265.             self.metadata_registered = False  # Only used for Google News
  1266.  
  1267.             self.set_handlers_to('result')
  1268.             return 'result'
  1269.  
  1270.         # Autocorrect
  1271.         if tag == 'span' and 'spell_orig' in self.classes(attrs) and attrs.get('id') != 'sifm':
  1272.             self.autocorrected = True
  1273.             return
  1274.         if tag == 'a' and 'spell' in self.classes(attrs) and attrs.get('id') != 'srfl':
  1275.             self.start_populating_textbuf()
  1276.             return 'spell'
  1277.  
  1278.         # Omitted results
  1279.         if tag == 'p' and attrs.get('id') == 'ofr':
  1280.             self.filtered = True
  1281.  
  1282.     @retrieve_tag_annotation
  1283.     def root_end(self, tag, annotation):
  1284.         if annotation == 'spell':
  1285.             self.stop_populating_textbuf()
  1286.             self.suggested_spelling = self.pop_textbuf()
  1287.  
  1288.     @annotate_tag
  1289.     def result_start(self, tag, attrs):
  1290.         if not ua and tag == 'span' and 'mime' in self.classes(attrs):
  1291.             self.start_populating_textbuf()
  1292.             return 'title_filetype'
  1293.  
  1294.         if not self.title_registered and tag == 'h3' and 'r' in self.classes(attrs):
  1295.             self.set_handlers_to('title')
  1296.             return 'title'
  1297.  
  1298.         if not self.abstract_registered and tag == 'div' and 's' in self.classes(attrs):
  1299.             self.set_handlers_to('abstract')
  1300.             return 'abstract'
  1301.  
  1302.         if not ua and not self.abstract_registered \
  1303.                 and tag == 'span' and 'st' in self.classes(attrs):
  1304.             self.start_populating_textbuf(lambda text: text + ' ')
  1305.             return 'abstract_gservices'
  1306.  
  1307.         if not self.sitelinks and tag == 'table':
  1308.             if ua or (not self.news and 'ts' not in self.classes(attrs)):
  1309.                 self.set_handlers_to('sitelink_table')
  1310.                 return 'sitelink_table'
  1311.  
  1312.         if self.news:
  1313.             if not self.metadata_registered and tag == 'div' and 'slp' in self.classes(attrs):
  1314.                 # Change metadata field separator from '-' to ', ' for better appearance
  1315.                 if ua:
  1316.                     self.start_populating_textbuf(lambda text: ', ' if text == '-' else text)
  1317.                 else:
  1318.                     self.start_populating_textbuf(lambda text:
  1319.                                                   text.replace(' -', ',', 1) if ' - ' in text else text)
  1320.                 return 'news_metadata'
  1321.  
  1322.             if not self.abstract_registered and tag == 'div' and 'st' in self.classes(attrs):
  1323.                 self.start_populating_textbuf()
  1324.                 return 'news_abstract'
  1325.  
  1326.     @retrieve_tag_annotation
  1327.     def result_end(self, tag, annotation):
  1328.         if annotation == 'result':
  1329.             if self.url:
  1330.                 self.index += 1
  1331.                 result = Result(self.index, self.title, self.url, self.abstract,
  1332.                                 metadata=self.metadata if self.metadata else None,
  1333.                                 sitelinks=self.sitelinks)
  1334.                 self.results.append(result)
  1335.             self.set_handlers_to('root')
  1336.         elif annotation == 'news_metadata':
  1337.             self.stop_populating_textbuf()
  1338.             self.metadata = self.pop_textbuf()
  1339.             self.metadata_registered = True
  1340.         elif annotation == 'news_abstract':
  1341.             self.stop_populating_textbuf()
  1342.             self.abstract = self.pop_textbuf()
  1343.             self.abstract_registered = True
  1344.         elif annotation == 'abstract_gservices':
  1345.             self.stop_populating_textbuf()
  1346.             self.abstract = self.pop_textbuf().replace('  ', ' ')
  1347.             self.abstract_registered = True
  1348.  
  1349.     @annotate_tag
  1350.     def title_start(self, tag, attrs):
  1351.         if ua and tag == 'span':
  1352.             # Print a space after the filetype indicator
  1353.             self.start_populating_textbuf(lambda text: text + ' ')
  1354.             return 'title_filetype'
  1355.         if tag == 'a' and 'href' in attrs:
  1356.             # Skip 'News for', 'Images for' search links
  1357.             if attrs['href'].startswith('/search'):
  1358.                 return
  1359.  
  1360.             # Skip card results
  1361.             if not ua and "fl" in self.classes(attrs):
  1362.                 return
  1363.  
  1364.             self.url = attrs['href']
  1365.             try:
  1366.                 start = self.url.index('?q=') + len('?q=')
  1367.                 end = self.url.index('&sa=', start)
  1368.                 self.url = urllib.parse.unquote_plus(self.url[start:end])
  1369.             except ValueError:
  1370.                 pass
  1371.             self.start_populating_textbuf()
  1372.             return 'title_link'
  1373.  
  1374.     @retrieve_tag_annotation
  1375.     def title_end(self, tag, annotation):
  1376.         if annotation == 'title_filetype':
  1377.             self.stop_populating_textbuf()
  1378.         elif annotation == 'title_link':
  1379.             self.stop_populating_textbuf()
  1380.             self.title = self.pop_textbuf()
  1381.             self.title_registered = True
  1382.         elif annotation == 'title':
  1383.             self.set_handlers_to('result')
  1384.  
  1385.     @annotate_tag
  1386.     def abstract_start(self, tag, attrs):
  1387.         if (not self.metadata_registered and
  1388.                 tag == 'div' and 'slp' in self.classes(attrs)):
  1389.             self.start_populating_textbuf()
  1390.             return 'result_metadata'
  1391.         if tag == 'span' and 'st' in self.classes(attrs):
  1392.             self.start_populating_textbuf()
  1393.             return 'abstract_text'
  1394.  
  1395.     @retrieve_tag_annotation
  1396.     def abstract_end(self, tag, annotation):
  1397.         if annotation == 'result_metadata':
  1398.             self.stop_populating_textbuf()
  1399.             self.metadata = self.pop_textbuf().strip().replace('\u200e', '')
  1400.             self.metadata_registered = True
  1401.         elif annotation == 'abstract_text':
  1402.             self.stop_populating_textbuf()
  1403.             self.abstract = self.pop_textbuf()
  1404.             self.abstract_registered = True
  1405.         elif annotation == 'abstract':
  1406.             self.set_handlers_to('result')
  1407.  
  1408.     @annotate_tag
  1409.     def sitelink_table_start(self, tag, attrs):
  1410.         if tag == 'td':
  1411.             # Initialize a new sitelink
  1412.             self.current_sitelink = Sitelink('', '', '')
  1413.             self.set_handlers_to('sitelink')
  1414.             return 'sitelink'
  1415.  
  1416.     @retrieve_tag_annotation
  1417.     def sitelink_table_end(self, tag, annotation):
  1418.         if annotation == 'sitelink_table':
  1419.             self.set_handlers_to('result')
  1420.  
  1421.     @annotate_tag
  1422.     def sitelink_start(self, tag, attrs):
  1423.         if tag == 'h3' and 'r' in self.classes(attrs):
  1424.             self.set_handlers_to('sitelink_title')
  1425.             return 'sitelink_title'
  1426.         if tag == 'div' and 'st' in self.classes(attrs):
  1427.             self.start_populating_textbuf()
  1428.             return 'sitelink_abstract'
  1429.  
  1430.     @retrieve_tag_annotation
  1431.     def sitelink_end(self, tag, annotation):
  1432.         if annotation == 'sitelink_abstract':
  1433.             self.stop_populating_textbuf()
  1434.             self.current_sitelink.abstract = self.pop_textbuf()
  1435.         elif annotation == 'sitelink':
  1436.             if self.current_sitelink.url:
  1437.                 self.sitelinks.append(self.current_sitelink)
  1438.             self.set_handlers_to('sitelink_table')
  1439.  
  1440.     @annotate_tag
  1441.     def sitelink_title_start(self, tag, attrs):
  1442.         if tag == 'a' and 'href' in attrs:
  1443.             self.current_sitelink.url = attrs['href']
  1444.             try:
  1445.                 start = self.current_sitelink.url.index('?q=') + len('?q=')
  1446.                 end = self.current_sitelink.url.index('&sa=', start)
  1447.                 self.current_sitelink.url = urllib.parse.unquote_plus(self.current_sitelink.url[start:end])
  1448.             except ValueError:
  1449.                 pass
  1450.             self.start_populating_textbuf()
  1451.             return 'sitelink_title_link'
  1452.  
  1453.     @retrieve_tag_annotation
  1454.     def sitelink_title_end(self, tag, annotation):
  1455.         if annotation == 'sitelink_title_link':
  1456.             self.stop_populating_textbuf()
  1457.             self.current_sitelink.title = self.pop_textbuf()
  1458.         elif annotation == 'sitelink_title':
  1459.             self.set_handlers_to('sitelink')
  1460.  
  1461.     # Generic methods
  1462.  
  1463.     # Set handle_starttag to SCOPE_start, and handle_endtag to SCOPE_end.
  1464.     def set_handlers_to(self, scope):
  1465.         self.handle_starttag = getattr(self, scope + '_start')
  1466.         self.handle_endtag = getattr(self, scope + '_end')
  1467.  
  1468.     def insert_annotation(self, tag, annotation):
  1469.         if tag not in self.tag_annotations:
  1470.             self.tag_annotations[tag] = []
  1471.         self.tag_annotations[tag].append(annotation)
  1472.  
  1473.     @annotate_tag
  1474.     def ignore_start(self, tag, attrs):
  1475.         pass
  1476.  
  1477.     @retrieve_tag_annotation
  1478.     def ignore_end(self, tag, annotation):
  1479.         if annotation and annotation.endswith('_ignored'):
  1480.             # Strip '-ignore' suffix from annotation to obtain the outer
  1481.             # context name.
  1482.             context = annotation[:-8]
  1483.             self.set_handlers_to(context)
  1484.  
  1485.     def start_populating_textbuf(self, data_transformer=None):
  1486.         if data_transformer is None:
  1487.             # Record data verbatim
  1488.             self.handle_data = self.record_data
  1489.         else:
  1490.             def record_transformed_data(data):
  1491.                 self.textbuf += data_transformer(data)
  1492.  
  1493.             self.handle_data = record_transformed_data
  1494.  
  1495.         self.handle_entityref = self.record_entityref
  1496.         self.handle_charref = self.record_charref
  1497.  
  1498.     def pop_textbuf(self):
  1499.         text = self.textbuf
  1500.         self.textbuf = ''
  1501.         return text
  1502.  
  1503.     def stop_populating_textbuf(self):
  1504.         self.handle_data = lambda data: None
  1505.         self.handle_entityref = lambda ref: None
  1506.         self.handle_charref = lambda ref: None
  1507.  
  1508.     def record_data(self, data):
  1509.         self.textbuf += data
  1510.  
  1511.     def record_entityref(self, ref):
  1512.         try:
  1513.             self.textbuf += chr(html.entities.name2codepoint[ref])
  1514.         except KeyError:
  1515.             # Entity name not found; most likely rather sloppy HTML
  1516.             # where a literal ampersand is not escaped; For instance,
  1517.             # the HTML response returned by
  1518.             #
  1519.             #     googler -c au -l ko expected
  1520.             #
  1521.             # contains the following tag
  1522.             #
  1523.             #     <p class="_e4b"><a href="...">expected market return s&p 500</a></p>
  1524.             #
  1525.             # where &p is interpreted by HTMLParser as an entity (this
  1526.             # behaviour seems to be specific to Python 2.7).
  1527.             self.textbuf += '&' + ref
  1528.  
  1529.     def record_charref(self, ref):
  1530.         if ref.startswith('x'):
  1531.             char = chr(int(ref[1:], 16))
  1532.         else:
  1533.             char = chr(int(ref))
  1534.         self.textbuf += char
  1535.  
  1536.     @staticmethod
  1537.     def classes(attrs):
  1538.         """Get tag's classes from its attribute dict."""
  1539.         return attrs.get('class', '').split()
  1540.  
  1541.  
  1542. class Sitelink(object):
  1543.     """Container for a sitelink."""
  1544.  
  1545.     def __init__(self, title, url, abstract):
  1546.         self.title = title
  1547.         self.url = url
  1548.         self.abstract = abstract
  1549.         self.index = ''
  1550.  
  1551.  
  1552. Colors = collections.namedtuple('Colors', 'index, title, url, metadata, abstract, prompt, reset')
  1553.  
  1554.  
  1555. class Result(object):
  1556.     """
  1557.    Container for one search result, with output helpers.
  1558.  
  1559.    Parameters
  1560.    ----------
  1561.    index : int or str
  1562.    title : str
  1563.    url : str
  1564.    abstract : str
  1565.    metadata : str, optional
  1566.        Only applicable to Google News results, with publisher name and
  1567.        publishing time.
  1568.    sitelinks : list, optional
  1569.        List of ``SiteLink`` objects.
  1570.  
  1571.    Attributes
  1572.    ----------
  1573.    index : str
  1574.    title : str
  1575.    url : str
  1576.    abstract : str
  1577.    metadata : str or None
  1578.    sitelinks : list
  1579.  
  1580.    Class Variables
  1581.    ---------------
  1582.    colors : str
  1583.  
  1584.    Methods
  1585.    -------
  1586.    print()
  1587.    jsonizable_object()
  1588.    urltable()
  1589.  
  1590.    """
  1591.  
  1592.     # Class variables
  1593.     colors = None
  1594.     urlexpand = True
  1595.  
  1596.     def __init__(self, index, title, url, abstract, metadata=None, sitelinks=None):
  1597.         index = str(index)
  1598.         self.index = index
  1599.         self.title = title
  1600.         self.url = url
  1601.         self.abstract = abstract
  1602.         self.metadata = metadata
  1603.         self.sitelinks = [] if sitelinks is None else sitelinks
  1604.  
  1605.         self._urltable = {index: url}
  1606.         subindex = 'a'
  1607.         for sitelink in sitelinks:
  1608.             fullindex = index + subindex
  1609.             sitelink.index = fullindex
  1610.             self._urltable[fullindex] = sitelink.url
  1611.             subindex = chr(ord(subindex) + 1)
  1612.  
  1613.     def _print_title_and_url(self, index, title, url, indent=0):
  1614.         colors = self.colors
  1615.  
  1616.         if not self.urlexpand:
  1617.             segments = urllib.parse.urlparse(url)
  1618.             url = '  [' + segments.netloc + ']'
  1619.  
  1620.         # Pad index and url with `indent` number of spaces
  1621.         index = ' ' * indent + str(index)
  1622.         url = ' ' * indent + url
  1623.         if colors:
  1624.             print(colors.index + index + colors.reset, end='')
  1625.             if self.urlexpand:
  1626.                 print(' ' + colors.title + title + colors.reset)
  1627.                 print(colors.url + url + colors.reset)
  1628.             else:
  1629.                 print(' ' + colors.title + title + colors.reset + colors.url + url + colors.reset)
  1630.         else:
  1631.             if self.urlexpand:
  1632.                 print(' %s %s\n%s' % (index, title, url))
  1633.             else:
  1634.                 print(' %s %s%s' % (index, title, url))
  1635.  
  1636.     def _print_metadata_and_abstract(self, abstract, metadata=None, indent=0):
  1637.         colors = self.colors
  1638.         try:
  1639.             columns, _ = os.get_terminal_size()
  1640.         except OSError:
  1641.             columns = 0
  1642.  
  1643.         if metadata:
  1644.             if colors:
  1645.                 print(colors.metadata + metadata + colors.reset)
  1646.             else:
  1647.                 print(metadata)
  1648.  
  1649.         if colors:
  1650.             print(colors.abstract, end='')
  1651.         if columns > indent + 1:
  1652.             # Try to fill to columns
  1653.             fillwidth = columns - indent - 1
  1654.             for line in textwrap.wrap(abstract.replace('\n', ''), width=fillwidth):
  1655.                 print('%s%s' % (' ' * indent, line))
  1656.             print('')
  1657.         else:
  1658.             print('%s\n' % abstract.replace('\n', ' '))
  1659.         if colors:
  1660.             print(colors.reset, end='')
  1661.  
  1662.     def print(self):
  1663.         """Print the result entry."""
  1664.         self._print_title_and_url(self.index, self.title, self.url)
  1665.         self._print_metadata_and_abstract(self.abstract, metadata=self.metadata)
  1666.  
  1667.         for sitelink in self.sitelinks:
  1668.             self._print_title_and_url(sitelink.index, sitelink.title, sitelink.url, indent=4)
  1669.             self._print_metadata_and_abstract(sitelink.abstract, indent=4)
  1670.  
  1671.     def jsonizable_object(self):
  1672.         """Return a JSON-serializable dict representing the result entry."""
  1673.         obj = {
  1674.             'title': self.title,
  1675.             'url': self.url,
  1676.             'abstract': self.abstract
  1677.         }
  1678.         if self.metadata:
  1679.             obj['metadata'] = self.metadata
  1680.         if self.sitelinks:
  1681.             obj['sitelinks'] = [sitelink.__dict__ for sitelink in self.sitelinks]
  1682.         return obj
  1683.  
  1684.     def urltable(self):
  1685.         """Return a index-to-URL table for the current result.
  1686.  
  1687.        Normally, the table contains only a single entry, but when the result
  1688.        contains sitelinks, all sitelinks are included in this table.
  1689.  
  1690.        Returns
  1691.        -------
  1692.        dict
  1693.            A dict mapping indices (strs) to URLs (also strs). Indices of
  1694.            sitelinks are the original index appended by lowercase letters a,
  1695.            b, c, etc.
  1696.  
  1697.        """
  1698.         return self._urltable
  1699.  
  1700.  
  1701. class GooglerCmdException(Exception):
  1702.     pass
  1703.  
  1704.  
  1705. class NoKeywordsException(GooglerCmdException):
  1706.     pass
  1707.  
  1708.  
  1709. def require_keywords(method):
  1710.     # Require keywords to be set before we run a GooglerCmd method. If
  1711.     # no keywords have been set, raise a NoKeywordsException.
  1712.     @functools.wraps(method)
  1713.     def enforced_method(self, *args, **kwargs):
  1714.         if not self.keywords:
  1715.             raise NoKeywordsException('No keywords.')
  1716.         method(self, *args, **kwargs)
  1717.  
  1718.     return enforced_method
  1719.  
  1720.  
  1721. def no_argument(method):
  1722.     # Normalize a do_* method of GooglerCmd that takes no argument to
  1723.     # one that takes an arg, but issue a warning when an nonempty
  1724.     # argument is given.
  1725.     @functools.wraps(method)
  1726.     def enforced_method(self, arg):
  1727.         if arg:
  1728.             method_name = arg.__name__
  1729.             command_name = method_name[3:] if method_name.startswith('do_') else method_name
  1730.             logger.warning("Argument to the '%s' command ignored.", command_name)
  1731.         method(self)
  1732.  
  1733.     return enforced_method
  1734.  
  1735.  
  1736. class GooglerCmd(object):
  1737.     """
  1738.    Command line interpreter and executor class for googler.
  1739.  
  1740.    Inspired by PSL cmd.Cmd.
  1741.  
  1742.    Parameters
  1743.    ----------
  1744.    opts : argparse.Namespace
  1745.        Options and/or arguments.
  1746.  
  1747.    Attributes
  1748.    ----------
  1749.    options : argparse.Namespace
  1750.        Options that are currently in effect. Read-only attribute.
  1751.    keywords : str or list or strs
  1752.        Current keywords. Read-only attribute
  1753.  
  1754.    Methods
  1755.    -------
  1756.    fetch()
  1757.    display_results(prelude='\n', json_output=False)
  1758.    fetch_and_display(prelude='\n', json_output=False, interactive=True)
  1759.    read_next_command()
  1760.    help()
  1761.    cmdloop()
  1762.    """
  1763.  
  1764.     # Class variables
  1765.     colors = None
  1766.  
  1767.     def __init__(self, opts):
  1768.         super().__init__()
  1769.  
  1770.         self._opts = opts
  1771.  
  1772.         self._google_url = GoogleUrl(opts)
  1773.         proxy = opts.proxy if hasattr(opts, 'proxy') else None
  1774.         self._conn = GoogleConnection(self._google_url.hostname, proxy=proxy,
  1775.                                       notweak=opts.notweak)
  1776.         atexit.register(self._conn.close)
  1777.  
  1778.         self.results = []
  1779.         self._autocorrected_to = None
  1780.         self._results_filtered = False
  1781.         self._urltable = {}
  1782.  
  1783.         self.promptcolor = True if os.getenv('DISABLE_PROMPT_COLOR') is None else False
  1784.  
  1785.     @property
  1786.     def options(self):
  1787.         """Current options."""
  1788.         return self._opts
  1789.  
  1790.     @property
  1791.     def keywords(self):
  1792.         """Current keywords."""
  1793.         return self._google_url.keywords
  1794.  
  1795.     @require_keywords
  1796.     def fetch(self):
  1797.         """Fetch a page and parse for results.
  1798.  
  1799.        Results are stored in ``self.results``.
  1800.  
  1801.        Raises
  1802.        ------
  1803.        GoogleConnectionError
  1804.  
  1805.        See Also
  1806.        --------
  1807.        fetch_and_display
  1808.  
  1809.        """
  1810.         # This method also sets self._results_filtered and
  1811.         # self._urltable.
  1812.         page = self._conn.fetch_page(self._google_url.relative())
  1813.  
  1814.         if logger.isEnabledFor(logging.DEBUG):
  1815.             import tempfile
  1816.             fd, tmpfile = tempfile.mkstemp(prefix='googler-response-')
  1817.             os.close(fd)
  1818.             with open(tmpfile, 'w', encoding='utf-8') as fp:
  1819.                 fp.write(page)
  1820.             logger.debug("Response body written to '%s'.", tmpfile)
  1821.  
  1822.         parser = GoogleParser(news=self._google_url.news)
  1823.         parser.feed(page)
  1824.  
  1825.         self.results = parser.results
  1826.         self._autocorrected_to = parser.suggested_spelling if parser.autocorrected else None
  1827.         self._results_filtered = parser.filtered
  1828.         self._urltable = {}
  1829.         for r in self.results:
  1830.             self._urltable.update(r.urltable())
  1831.  
  1832.     @require_keywords
  1833.     def display_results(self, prelude='\n', json_output=False):
  1834.         """Display results stored in ``self.results``.
  1835.  
  1836.        Parameters
  1837.        ----------
  1838.        See `fetch_and_display`.
  1839.  
  1840.        """
  1841.         if json_output:
  1842.             # JSON output
  1843.             import json
  1844.             results_object = [r.jsonizable_object() for r in self.results]
  1845.             print(json.dumps(results_object, indent=2, sort_keys=True, ensure_ascii=False))
  1846.         else:
  1847.             # Regular output
  1848.             if not self.results:
  1849.                 print('No results.', file=sys.stderr)
  1850.             else:
  1851.                 sys.stderr.write(prelude)
  1852.                 for r in self.results:
  1853.                     r.print()
  1854.  
  1855.     @require_keywords
  1856.     def fetch_and_display(self, prelude='\n', json_output=False, interactive=True):
  1857.         """Fetch a page and display results.
  1858.  
  1859.        Results are stored in ``self.results``.
  1860.  
  1861.        Parameters
  1862.        ----------
  1863.        prelude : str, optional
  1864.            A string that is written to stderr before showing actual results,
  1865.            usually serving as a separator. Default is an empty line.
  1866.        json_output : bool, optional
  1867.            Whether to dump results in JSON format. Default is False.
  1868.        interactive : bool, optional
  1869.            Whether to show contextual instructions, when e.g. Google
  1870.            has filtered the results. Default is True.
  1871.  
  1872.        Raises
  1873.        ------
  1874.        GoogleConnectionError
  1875.  
  1876.        See Also
  1877.        --------
  1878.        fetch
  1879.        display_results
  1880.  
  1881.        """
  1882.         self.fetch()
  1883.         colors = self.colors
  1884.         if self._autocorrected_to:
  1885.             if colors:
  1886.                 # Underline the keywords
  1887.                 autocorrected_to = '\x1b[4m' + self._autocorrected_to + '\x1b[24m'
  1888.             else:
  1889.                 autocorrected_to = self._autocorrected_to
  1890.             autocorrect_info = ('Showing results for %s; enter "x" for an exact search.' %
  1891.                                 autocorrected_to)
  1892.             printerr('')
  1893.             if colors:
  1894.                 printerr(colors.prompt + autocorrect_info + colors.reset)
  1895.             else:
  1896.                 printerr('** ' + autocorrect_info)
  1897.         self.display_results(prelude=prelude, json_output=json_output)
  1898.         if self._results_filtered:
  1899.             unfilter_info = 'Enter "unfilter" to show similar results Google omitted.'
  1900.             if colors:
  1901.                 printerr(colors.prompt + unfilter_info + colors.reset)
  1902.             else:
  1903.                 printerr('** ' + unfilter_info)
  1904.             printerr('')
  1905.  
  1906.     def read_next_command(self):
  1907.         """Show omniprompt and read user command line.
  1908.  
  1909.        Command line is always stripped, and each consecutive group of
  1910.        whitespace is replaced with a single space character. If the
  1911.        command line is empty after stripping, when ignore it and keep
  1912.        reading. Exit with status 0 if we get EOF or an empty line
  1913.        (pre-strip, that is, a raw <enter>) twice in a row.
  1914.  
  1915.        The new command line (non-empty) is stored in ``self.cmd``.
  1916.  
  1917.        """
  1918.         colors = self.colors
  1919.         message = 'googler (? for help)'
  1920.         prompt = (colors.prompt + message + colors.reset + ' ') if (colors and self.promptcolor) else (message + ': ')
  1921.         enter_count = 0
  1922.         while True:
  1923.             try:
  1924.                 cmd = input(prompt)
  1925.             except EOFError:
  1926.                 sys.exit(0)
  1927.  
  1928.             if not cmd:
  1929.                 enter_count += 1
  1930.                 if enter_count == 2:
  1931.                     # Double <enter>
  1932.                     sys.exit(0)
  1933.             else:
  1934.                 enter_count = 0
  1935.  
  1936.             cmd = ' '.join(cmd.split())
  1937.             if cmd:
  1938.                 self.cmd = cmd
  1939.                 break
  1940.  
  1941.     @staticmethod
  1942.     def help():
  1943.         GooglerArgumentParser.print_omniprompt_help(sys.stderr)
  1944.         printerr('')
  1945.  
  1946.     @require_keywords
  1947.     @no_argument
  1948.     def do_first(self):
  1949.         try:
  1950.             self._google_url.first_page()
  1951.         except ValueError as e:
  1952.             print(e, file=sys.stderr)
  1953.             return
  1954.  
  1955.         self.fetch_and_display()
  1956.  
  1957.     def do_google(self, arg):
  1958.         # Update keywords and reconstruct URL
  1959.         self._opts.keywords = arg
  1960.         self._google_url = GoogleUrl(self._opts)
  1961.         self.fetch_and_display()
  1962.  
  1963.     @require_keywords
  1964.     @no_argument
  1965.     def do_next(self):
  1966.         # If > 5 results are being fetched each time,
  1967.         # block next when no parsed results in current fetch
  1968.         if not self.results and self._google_url._num > 5:
  1969.             printerr('No results.')
  1970.         else:
  1971.             self._google_url.next_page()
  1972.             self.fetch_and_display()
  1973.  
  1974.     @require_keywords
  1975.     def do_open(self, *args):
  1976.         if not args:
  1977.             open_url(self._google_url.full())
  1978.             return
  1979.  
  1980.         for nav in args:
  1981.             if nav == 'a':
  1982.                 for key, value in sorted(self._urltable.items()):
  1983.                     open_url(self._urltable[key])
  1984.             elif nav in self._urltable:
  1985.                 open_url(self._urltable[nav])
  1986.             elif '-' in nav:
  1987.                 try:
  1988.                     vals = [int(x) for x in nav.split('-')]
  1989.                     if (len(vals) != 2):
  1990.                         printerr('Invalid range %s.' % nav)
  1991.                         continue
  1992.  
  1993.                     if vals[0] > vals[1]:
  1994.                         vals[0], vals[1] = vals[1], vals[0]
  1995.  
  1996.                     for _id in range(vals[0], vals[1] + 1):
  1997.                         if str(_id) in self._urltable:
  1998.                             open_url(self._urltable[str(_id)])
  1999.                         else:
  2000.                             printerr('Invalid index %s.' % _id)
  2001.                 except ValueError:
  2002.                     printerr('Invalid range %s.' % nav)
  2003.             else:
  2004.                 printerr('Invalid index %s.' % nav)
  2005.  
  2006.     @require_keywords
  2007.     @no_argument
  2008.     def do_previous(self):
  2009.         try:
  2010.             self._google_url.prev_page()
  2011.         except ValueError as e:
  2012.             print(e, file=sys.stderr)
  2013.             return
  2014.  
  2015.         self.fetch_and_display()
  2016.  
  2017.     @require_keywords
  2018.     @no_argument
  2019.     def do_exact(self):
  2020.         # Reset start to 0 when exact is applied.
  2021.         self._google_url.update(start=0, exact=True)
  2022.         self.fetch_and_display()
  2023.  
  2024.     @require_keywords
  2025.     @no_argument
  2026.     def do_unfilter(self):
  2027.         # Reset start to 0 when unfilter is applied.
  2028.         self._google_url.update(start=0)
  2029.         self._google_url.set_queries(filter=0)
  2030.         self.fetch_and_display()
  2031.  
  2032.     def cmdloop(self):
  2033.         """Run REPL."""
  2034.         if self.keywords:
  2035.             self.fetch_and_display()
  2036.         else:
  2037.             printerr('Please initiate a query.')
  2038.  
  2039.         while True:
  2040.             self.read_next_command()
  2041.             # TODO: Automatic dispatcher
  2042.             #
  2043.             # We can't write a dispatcher for now because that could
  2044.             # change behaviour of the prompt. However, we have already
  2045.             # laid a lot of ground work for the dispatcher, e.g., the
  2046.             # `no_argument' decorator.
  2047.             try:
  2048.                 cmd = self.cmd
  2049.                 if cmd == 'f':
  2050.                     self.do_first('')
  2051.                 elif cmd.startswith('g '):
  2052.                     self.do_google(cmd[2:])
  2053.                 elif cmd == 'n':
  2054.                     self.do_next('')
  2055.                 elif cmd == 'o':
  2056.                     self.do_open()
  2057.                 elif cmd.startswith('o '):
  2058.                     self.do_open(*cmd[2:].split())
  2059.                 elif cmd.startswith('O '):
  2060.                     open_url.override_text_browser = True
  2061.                     self.do_open(*cmd[2:].split())
  2062.                     open_url.override_text_browser = False
  2063.                 elif cmd == 'p':
  2064.                     self.do_previous('')
  2065.                 elif cmd == 'q':
  2066.                     break
  2067.                 elif cmd == 'x':
  2068.                     self.do_exact('')
  2069.                 elif cmd == 'unfilter':
  2070.                     self.do_unfilter('')
  2071.                 elif cmd == '?':
  2072.                     self.help()
  2073.                 elif cmd in self._urltable:
  2074.                     open_url(self._urltable[cmd])
  2075.                 elif self.keywords and cmd.isdigit() and int(cmd) < 100:
  2076.                     printerr('Index out of bound. To search for the number, use g.')
  2077.                 elif cmd == 'u':
  2078.                     Result.urlexpand = not Result.urlexpand
  2079.                     printerr('url expansion toggled.')
  2080.                 elif cmd.startswith('c ') and cmd[2:].isdigit():
  2081.                     try:
  2082.                         # try copying the url to clipboard using native utilities
  2083.                         if sys.platform.startswith(('linux', 'freebsd', 'openbsd')):
  2084.                             if shutil.which('xsel') is None:
  2085.                                 raise FileNotFoundError
  2086.                             copier_params = ['xsel', '-b', '-i']
  2087.                         elif sys.platform == 'darwin':
  2088.                             copier_params = ['pbcopy']
  2089.                         elif sys.platform == 'win32':
  2090.                             copier_params = ['clip']
  2091.                         else:
  2092.                             copier_params = []
  2093.  
  2094.                         if not copier_params:
  2095.                             printerr('operating system not identified')
  2096.                         else:
  2097.                             Popen(copier_params, stdin=PIPE, stdout=DEVNULL,
  2098.                                   stderr=DEVNULL).communicate(self._urltable[cmd[2:]].encode('utf-8'))
  2099.                     except FileNotFoundError:
  2100.                         printerr('xsel missing')
  2101.                     except Exception:
  2102.                         raise NoKeywordsException
  2103.                 else:
  2104.                     self.do_google(cmd)
  2105.             except NoKeywordsException:
  2106.                 printerr('Initiate a query first.')
  2107.  
  2108.  
  2109. class GooglerArgumentParser(argparse.ArgumentParser):
  2110.     """Custom argument parser for googler."""
  2111.  
  2112.     # Print omniprompt help
  2113.     @staticmethod
  2114.     def print_omniprompt_help(file=None):
  2115.         file = sys.stderr if file is None else file
  2116.         file.write(textwrap.dedent("""
  2117.        omniprompt keys:
  2118.          n, p                  fetch the next or previous set of search results
  2119.          index                 open the result corresponding to index in browser
  2120.          f                     jump to the first page
  2121.          o [index|range|a ...] open space-separated result indices, numeric ranges
  2122.                                (sitelinks unsupported in ranges), or all, in browser
  2123.                                open the current search in browser, if no arguments
  2124.          O [index|range|a ...] like key 'o', but try to open in a GUI browser
  2125.          g keywords            new Google search for 'keywords' with original options
  2126.                                should be used to search omniprompt keys and indices
  2127.          c index               copy url to clipboard
  2128.          u                     toggle url expansion
  2129.          q, ^D, double Enter   exit googler
  2130.          ?                     show omniprompt help
  2131.          *                     other inputs issue a new search with original options
  2132.        """))
  2133.  
  2134.     # Print information on googler
  2135.     @staticmethod
  2136.     def print_general_info(file=None):
  2137.         file = sys.stderr if file is None else file
  2138.         file.write(textwrap.dedent("""
  2139.        Version %s
  2140.        Copyright © 2008 Henri Hakkinen
  2141.        Copyright © 2015-2018 Arun Prakash Jana <engineerarun@gmail.com>
  2142.        Zhiming Wang <zmwangx@gmail.com>
  2143.        License: GPLv3
  2144.        Webpage: https://github.com/jarun/googler
  2145.        """ % _VERSION_))
  2146.  
  2147.     # Augment print_help to print more than synopsis and options
  2148.     def print_help(self, file=None):
  2149.         super().print_help(file)
  2150.         self.print_omniprompt_help(file)
  2151.         self.print_general_info(file)
  2152.  
  2153.     # Automatically print full help text on error
  2154.     def error(self, message):
  2155.         sys.stderr.write('%s: error: %s\n\n' % (self.prog, message))
  2156.         self.print_help(sys.stderr)
  2157.         self.exit(2)
  2158.  
  2159.     # Type guards
  2160.     @staticmethod
  2161.     def positive_int(arg):
  2162.         """Try to convert a string into a positive integer."""
  2163.         try:
  2164.             n = int(arg)
  2165.             assert n > 0
  2166.             return n
  2167.         except (ValueError, AssertionError):
  2168.             raise argparse.ArgumentTypeError('%s is not a positive integer' % arg)
  2169.  
  2170.     @staticmethod
  2171.     def nonnegative_int(arg):
  2172.         """Try to convert a string into a nonnegative integer."""
  2173.         try:
  2174.             n = int(arg)
  2175.             assert n >= 0
  2176.             return n
  2177.         except (ValueError, AssertionError):
  2178.             raise argparse.ArgumentTypeError('%s is not a non-negative integer' % arg)
  2179.  
  2180.     @staticmethod
  2181.     def is_duration(arg):
  2182.         """Check if a string is a valid duration accepted by Google.
  2183.  
  2184.        A valid duration is of the form dNUM, where d is a single letter h
  2185.        (hour), d (day), w (week), m (month), or y (year), and NUM is a
  2186.        non-negative integer.
  2187.        """
  2188.         try:
  2189.             if arg[0] not in ('h', 'd', 'w', 'm', 'y') or int(arg[1:]) < 0:
  2190.                 raise ValueError
  2191.         except (TypeError, IndexError, ValueError):
  2192.             raise argparse.ArgumentTypeError('%s is not a valid duration' % arg)
  2193.         return arg
  2194.  
  2195.     @staticmethod
  2196.     def is_colorstr(arg):
  2197.         """Check if a string is a valid color string."""
  2198.         try:
  2199.             assert len(arg) == 6
  2200.             for c in arg:
  2201.                 assert c in COLORMAP
  2202.         except AssertionError:
  2203.             raise argparse.ArgumentTypeError('%s is not a valid color string' % arg)
  2204.         return arg
  2205.  
  2206.  
  2207. # Self-upgrade mechanism
  2208.  
  2209. def system_is_windows():
  2210.     """Checks if the underlying system is Windows (Cygwin included)."""
  2211.     return sys.platform in {'win32', 'cygwin'}
  2212.  
  2213.  
  2214. def download_latest_googler(include_git=False):
  2215.     """Download latest googler to a temp file.
  2216.  
  2217.    By default, the latest released version is downloaded, but if
  2218.    `include_git` is specified, then the latest git master is downloaded
  2219.    instead.
  2220.  
  2221.    Parameters
  2222.    ----------
  2223.    include_git : bool, optional
  2224.        Download from git master. Default is False.
  2225.  
  2226.    Returns
  2227.    -------
  2228.    (git_ref, path): tuple
  2229.         A tuple containing the git reference (either name of the latest
  2230.         tag or SHA of the latest commit) and path to the downloaded
  2231.         file.
  2232.  
  2233.    """
  2234.     import urllib.request
  2235.  
  2236.     if include_git:
  2237.         # Get SHA of latest commit on master
  2238.         request = urllib.request.Request('%s/commits/master' % API_REPO_BASE,
  2239.                                          headers={'Accept': 'application/vnd.github.v3.sha'})
  2240.         response = urllib.request.urlopen(request)
  2241.         if response.status != 200:
  2242.             raise http.client.HTTPException(response.reason)
  2243.         git_ref = response.read().decode('utf-8')
  2244.     else:
  2245.         # Get name of latest tag
  2246.         request = urllib.request.Request('%s/releases?per_page=1' % API_REPO_BASE,
  2247.                                          headers={'Accept': 'application/vnd.github.v3+json'})
  2248.         response = urllib.request.urlopen(request)
  2249.         if response.status != 200:
  2250.             raise http.client.HTTPException(response.reason)
  2251.         import json
  2252.         git_ref = json.loads(response.read().decode('utf-8'))[0]['tag_name']
  2253.  
  2254.     # Download googler to a tempfile
  2255.     googler_download_url = '%s/%s/googler' % (RAW_DOWNLOAD_REPO_BASE, git_ref)
  2256.     printerr('Downloading %s' % googler_download_url)
  2257.     request = urllib.request.Request(googler_download_url,
  2258.                                      headers={'Accept-Encoding': 'gzip'})
  2259.     import tempfile
  2260.     fd, path = tempfile.mkstemp()
  2261.     atexit.register(lambda: os.remove(path) if os.path.exists(path) else None)
  2262.     os.close(fd)
  2263.     with open(path, 'wb') as fp:
  2264.         with urllib.request.urlopen(request) as response:
  2265.             if response.status != 200:
  2266.                 raise http.client.HTTPException(response.reason)
  2267.             payload = response.read()
  2268.             try:
  2269.                 fp.write(gzip.decompress(payload))
  2270.             except OSError:
  2271.                 fp.write(payload)
  2272.     return git_ref, path
  2273.  
  2274.  
  2275. def self_replace(path):
  2276.     """Replace the current script with a specified file.
  2277.  
  2278.    Both paths (the specified path and path to the current script) are
  2279.    resolved to absolute, symlink-free paths. Upon replacement, the
  2280.    owner and mode signatures of the current script are preserved. The
  2281.    caller needs to have the necessary permissions.
  2282.  
  2283.    Replacement won't happen if the specified file is the same
  2284.    (content-wise) as the current script.
  2285.  
  2286.    Parameters
  2287.    ----------
  2288.    path : str
  2289.        Path to the replacement file.
  2290.  
  2291.    Returns
  2292.    -------
  2293.    bool
  2294.        True if replaced, False if skipped (specified file is the same
  2295.        as the current script).
  2296.  
  2297.    """
  2298.     if system_is_windows():
  2299.         raise NotImplementedError('Self upgrade not supported on Windows.')
  2300.  
  2301.     import filecmp
  2302.     import shutil
  2303.  
  2304.     path = os.path.realpath(path)
  2305.     self_path = os.path.realpath(__file__)
  2306.  
  2307.     if filecmp.cmp(path, self_path):
  2308.         return False
  2309.  
  2310.     self_stat = os.stat(self_path)
  2311.     os.chown(path, self_stat.st_uid, self_stat.st_gid)
  2312.     os.chmod(path, self_stat.st_mode)
  2313.  
  2314.     shutil.move(path, self_path)
  2315.     return True
  2316.  
  2317.  
  2318. def self_upgrade(include_git=False):
  2319.     """Perform in-place self-upgrade.
  2320.  
  2321.    Parameters
  2322.    ----------
  2323.    include_git : bool, optional
  2324.        See `download_latest_googler`. Default is False.
  2325.  
  2326.    """
  2327.     git_ref, path = download_latest_googler(include_git=include_git)
  2328.     if self_replace(path):
  2329.         printerr('Upgraded to %s.' % git_ref)
  2330.     else:
  2331.         printerr('Already up to date.')
  2332.  
  2333.  
  2334. # Miscellaneous functions
  2335.  
  2336. def python_version():
  2337.     return '%d.%d.%d' % sys.version_info[:3]
  2338.  
  2339.  
  2340. def https_proxy_from_environment():
  2341.     return os.getenv('https_proxy')
  2342.  
  2343.  
  2344. def parse_proxy_spec(proxyspec):
  2345.     if '://' in proxyspec:
  2346.         pos = proxyspec.find('://')
  2347.         scheme = proxyspec[:pos]
  2348.         proxyspec = proxyspec[pos+3:]
  2349.         if scheme.lower() != 'http':
  2350.             # Only support HTTP proxies.
  2351.             #
  2352.             # In particular, we don't support HTTPS proxies since we
  2353.             # only speak plain HTTP to the proxy server, so don't give
  2354.             # users a false sense of security.
  2355.             raise NotImplementedError('Unsupported proxy scheme %s.' % scheme)
  2356.  
  2357.     if '@' in proxyspec:
  2358.         pos = proxyspec.find('@')
  2359.         user_passwd = urllib.parse.unquote(proxyspec[:pos])
  2360.         # Remove trailing '/' if any
  2361.         host_port = proxyspec[pos+1:].rstrip('/')
  2362.     else:
  2363.         user_passwd = None
  2364.         host_port = proxyspec
  2365.  
  2366.     if ':' not in host_port:
  2367.         # Use port 1080 as default, following curl.
  2368.         host_port += ':1080'
  2369.  
  2370.     return user_passwd, host_port
  2371.  
  2372.  
  2373. # Query autocompleter
  2374.  
  2375. # This function is largely experimental and could raise any exception;
  2376. # you should be prepared to catch anything. When it works though, it
  2377. # returns a list of strings the prefix could autocomplete to (however,
  2378. # it is not guaranteed that they start with the specified prefix; for
  2379. # instance, they won't if the specified prefix ends in a punctuation
  2380. # mark.)
  2381. def completer_fetch_completions(prefix):
  2382.     import json
  2383.     import re
  2384.     import urllib.request
  2385.  
  2386.     # One can pass the 'hl' query param to specify the language. We
  2387.     # ignore that for now.
  2388.     api_url = ('https://www.google.com/complete/search?client=psy-ab&q=%s' %
  2389.                urllib.parse.quote(prefix, safe=''))
  2390.     # A timeout of 3 seconds seems to be overly generous already.
  2391.     resp = urllib.request.urlopen(api_url, timeout=3)
  2392.     charset = resp.headers.get_content_charset()
  2393.     logger.debug('Completions charset: %s', charset)
  2394.     respobj = json.loads(resp.read().decode(charset))
  2395.  
  2396.     # The response object, once parsed as JSON, should look like
  2397.     #
  2398.     # ['git',
  2399.     #  [['git<b>hub</b>', 0],
  2400.     #   ['git', 0],
  2401.     #   ['git<b>lab</b>', 0],
  2402.     #   ['git<b> stash</b>', 0]],
  2403.     #  {'q': 'oooAhRzoChqNmMbNaaDKXk1YY4k', 't': {'bpc': False, 'tlw': False}}]
  2404.     #
  2405.     # Note the each result entry need not have two members; e.g., for
  2406.     # 'gi', there is an entry ['gi<b>f</b>', 0, [131]].
  2407.     HTML_TAG = re.compile(r'<[^>]+>')
  2408.     return [HTML_TAG.sub('', entry[0]) for entry in respobj[1]]
  2409.  
  2410.  
  2411. def completer_run(prefix):
  2412.     if prefix:
  2413.         completions = completer_fetch_completions(prefix)
  2414.         if completions:
  2415.             print('\n'.join(completions))
  2416.     sys.exit(0)
  2417.  
  2418.  
  2419. def parse_args(args=None, namespace=None):
  2420.     """Parse googler arguments/options.
  2421.  
  2422.    Parameters
  2423.    ----------
  2424.    args : list, optional
  2425.        Arguments to parse. Default is ``sys.argv``.
  2426.    namespace : argparse.Namespace
  2427.        Namespace to write to. Default is a new namespace.
  2428.  
  2429.    Returns
  2430.    -------
  2431.    argparse.Namespace
  2432.        Namespace with parsed arguments / options.
  2433.  
  2434.    """
  2435.  
  2436.     colorstr_env = os.getenv('GOOGLER_COLORS')
  2437.  
  2438.     argparser = GooglerArgumentParser(description='Google from the command-line.')
  2439.     addarg = argparser.add_argument
  2440.     addarg('-s', '--start', type=argparser.nonnegative_int, default=0,
  2441.            metavar='N', help='start at the Nth result')
  2442.     addarg('-n', '--count', dest='num', type=argparser.positive_int,
  2443.            default=10, metavar='N', help='show N results (default 10)')
  2444.     addarg('-N', '--news', action='store_true',
  2445.            help='show results from news section')
  2446.     addarg('-c', '--tld', metavar='TLD',
  2447.            help="""country-specific search with top-level domain .TLD, e.g., 'in'
  2448.           for India""")
  2449.     addarg('-l', '--lang', metavar='LANG', help='display in language LANG')
  2450.     addarg('-x', '--exact', action='store_true',
  2451.            help='disable automatic spelling correction')
  2452.     addarg('-C', '--nocolor', dest='colorize', action='store_false',
  2453.            help='disable color output')
  2454.     addarg('--colors', dest='colorstr', type=argparser.is_colorstr,
  2455.            default=colorstr_env if colorstr_env else 'GKlgxy', metavar='COLORS',
  2456.            help='set output colors (see man page for details)')
  2457.     addarg('-j', '--first', '--lucky', dest='lucky', action='store_true',
  2458.            help='open the first result in web browser and exit')
  2459.     addarg('-t', '--time', dest='duration', type=argparser.is_duration,
  2460.            metavar='dN', help='time limit search '
  2461.            '[h5 (5 hrs), d5 (5 days), w5 (5 weeks), m5 (5 months), y5 (5 years)]')
  2462.     addarg('-w', '--site', dest='sites', action='append', metavar='SITE',
  2463.            help='search a site using Google')
  2464.     addarg('--unfilter', action='store_true', help='do not omit similar results')
  2465.     addarg('-p', '--proxy', default=https_proxy_from_environment(),
  2466.            help="""tunnel traffic through an HTTP proxy;
  2467.           PROXY is of the form [http://][user:password@]proxyhost[:port]""")
  2468.     addarg('--noua', action='store_true', help='disable user agent')
  2469.     addarg('--notweak', action='store_true',
  2470.            help='disable TCP optimizations and forced TLS 1.2')
  2471.     addarg('--json', action='store_true',
  2472.            help='output in JSON format; implies --noprompt')
  2473.     addarg('--url-handler', metavar='UTIL',
  2474.            help='custom script or cli utility to open results')
  2475.     addarg('--show-browser-logs', action='store_true',
  2476.            help='do not suppress browser output (stdout and stderr)')
  2477.     addarg('--np', '--noprompt', dest='noninteractive', action='store_true',
  2478.            help='search and exit, do not prompt')
  2479.     addarg('keywords', nargs='*', metavar='KEYWORD', help='search keywords')
  2480.     if ENABLE_SELF_UPGRADE_MECHANISM and not system_is_windows():
  2481.         addarg('-u', '--upgrade', action='store_true',
  2482.                help='perform in-place self-upgrade')
  2483.         addarg('--include-git', action='store_true',
  2484.                help='when used with --upgrade, upgrade to latest git master')
  2485.     addarg('-v', '--version', action='version', version=_VERSION_)
  2486.     addarg('-d', '--debug', action='store_true', help='enable debugging')
  2487.     addarg('--complete', help=argparse.SUPPRESS)
  2488.  
  2489.     return argparser.parse_args(args, namespace)
  2490.  
  2491.  
  2492. def main():
  2493.     global ua
  2494.  
  2495.     try:
  2496.         opts = parse_args()
  2497.  
  2498.         # Set logging level
  2499.         if opts.debug:
  2500.             logger.setLevel(logging.DEBUG)
  2501.             logger.debug('googler version %s', _VERSION_)
  2502.             logger.debug('Python version %s', python_version())
  2503.  
  2504.         # Handle query completer
  2505.         if opts.complete is not None:
  2506.             completer_run(opts.complete)
  2507.  
  2508.         # Handle self-upgrade
  2509.         if hasattr(opts, 'upgrade') and opts.upgrade:
  2510.             self_upgrade(include_git=opts.include_git)
  2511.             sys.exit(0)
  2512.  
  2513.         check_stdout_encoding()
  2514.  
  2515.         if opts.keywords:
  2516.             try:
  2517.                 # Add cmdline args to readline history
  2518.                 readline.add_history(' '.join(opts.keywords))
  2519.             except Exception:
  2520.                 pass
  2521.  
  2522.         # Set colors
  2523.         if opts.colorize:
  2524.             colors = Colors(*[COLORMAP[c] for c in opts.colorstr], reset=COLORMAP['x'])
  2525.         else:
  2526.             colors = None
  2527.         Result.colors = colors
  2528.         Result.urlexpand = True if os.getenv('DISABLE_URL_EXPANSION') is None else False
  2529.         GooglerCmd.colors = colors
  2530.  
  2531.         if opts.url_handler is not None:
  2532.             open_url.url_handler = opts.url_handler
  2533.         else:
  2534.             # Set text browser override to False
  2535.             open_url.override_text_browser = False
  2536.  
  2537.             # Handle browser output suppression
  2538.             if opts.show_browser_logs or (os.getenv('BROWSER') in text_browsers):
  2539.                 open_url.suppress_browser_output = False
  2540.             else:
  2541.                 open_url.suppress_browser_output = True
  2542.  
  2543.         if opts.noua:
  2544.             logger.debug('User Agent is disabled')
  2545.             ua = False
  2546.  
  2547.         repl = GooglerCmd(opts)
  2548.  
  2549.         if opts.json or opts.lucky or opts.noninteractive:
  2550.             # Non-interactive mode
  2551.             repl.fetch()
  2552.             if opts.lucky:
  2553.                 if repl.results:
  2554.                     open_url(repl.results[0].url)
  2555.                 else:
  2556.                     print('No results.', file=sys.stderr)
  2557.             else:
  2558.                 repl.display_results(prelude='', json_output=opts.json)
  2559.             sys.exit(0)
  2560.         else:
  2561.             # Interactive mode
  2562.             repl.cmdloop()
  2563.     except Exception as e:
  2564.         # With debugging on, let the exception through for a traceback;
  2565.         # otherwise, only print the exception error message.
  2566.         if logger.isEnabledFor(logging.DEBUG):
  2567.             raise
  2568.         else:
  2569.             logger.error(e)
  2570.             sys.exit(1)
  2571.  
  2572. if __name__ == '__main__':
  2573.     main()
Add Comment
Please, Sign In to add comment