123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340 |
- """Google (Web)
- For detailed description of the *REST-full* API see: `Query Parameter
- Definitions`_.
- .. _Query Parameter Definitions:
- https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
- """
- from urllib.parse import urlencode, urlparse
- from random import random
- from lxml import html
- from searx import logger
- from searx.utils import match_language, extract_text, eval_xpath, eval_xpath_list, eval_xpath_getindex
- from searx.exceptions import SearxEngineCaptchaException
- logger = logger.getChild('google engine')
- about = {
- "website": 'https://www.google.com',
- "wikidata_id": 'Q9366',
- "official_api_documentation": 'https://developers.google.com/custom-search/',
- "use_official_api": False,
- "require_api_key": False,
- "results": 'HTML',
- }
- categories = ['general']
- paging = True
- time_range_support = True
- safesearch = True
- use_mobile_ui = False
- supported_languages_url = 'https://www.google.com/preferences?#languages'
- google_domains = {
- 'BG': 'google.bg',
- 'CZ': 'google.cz',
- 'DE': 'google.de',
- 'DK': 'google.dk',
- 'AT': 'google.at',
- 'CH': 'google.ch',
- 'GR': 'google.gr',
- 'AU': 'google.com.au',
- 'CA': 'google.ca',
- 'GB': 'google.co.uk',
- 'ID': 'google.co.id',
- 'IE': 'google.ie',
- 'IN': 'google.co.in',
- 'MY': 'google.com.my',
- 'NZ': 'google.co.nz',
- 'PH': 'google.com.ph',
- 'SG': 'google.com.sg',
- 'US': 'google.com',
- 'ZA': 'google.co.za',
- 'AR': 'google.com.ar',
- 'CL': 'google.cl',
- 'ES': 'google.es',
- 'MX': 'google.com.mx',
- 'EE': 'google.ee',
- 'FI': 'google.fi',
- 'BE': 'google.be',
- 'FR': 'google.fr',
- 'IL': 'google.co.il',
- 'HR': 'google.hr',
- 'HU': 'google.hu',
- 'IT': 'google.it',
- 'JP': 'google.co.jp',
- 'KR': 'google.co.kr',
- 'LT': 'google.lt',
- 'LV': 'google.lv',
- 'NO': 'google.no',
- 'NL': 'google.nl',
- 'PL': 'google.pl',
- 'BR': 'google.com.br',
- 'PT': 'google.pt',
- 'RO': 'google.ro',
- 'RU': 'google.ru',
- 'SK': 'google.sk',
- 'SI': 'google.si',
- 'SE': 'google.se',
- 'TH': 'google.co.th',
- 'TR': 'google.com.tr',
- 'UA': 'google.com.ua',
- 'CN': 'google.com.hk',
- 'HK': 'google.com.hk',
- 'TW': 'google.com.tw'
- }
- time_range_dict = {
- 'day': 'd',
- 'week': 'w',
- 'month': 'm',
- 'year': 'y'
- }
- filter_mapping = {
- 0: 'off',
- 1: 'medium',
- 2: 'high'
- }
- results_xpath = '//div[contains(@class, "MjjYud")]'
- title_xpath = './/h3[1]'
- href_xpath = './/a/@href'
- content_xpath = './/div[@data-sncf]'
- results_xpath_mobile_ui = '//div[contains(@class, "g ")]'
- g_section_with_header = './g-section-with-header'
- suggestion_xpath = '//div[contains(@class, "card-section")]//a'
- spelling_suggestion_xpath = '//div[@class="med"]/p/a'
- def get_lang_info(params, lang_list, custom_aliases, supported_any_language):
- ret_val = {}
- _lang = params['language']
- _any_language = _lang.lower() == 'all'
- if _any_language:
- _lang = 'en-US'
- language = match_language(_lang, lang_list, custom_aliases)
- ret_val['language'] = language
-
- _l = _lang.split('-')
-
- if len(_l) == 2:
- country = _l[1]
- else:
- country = _l[0].upper()
- if country == 'EN':
- country = 'US'
- ret_val['country'] = country
-
- lang_country = '%s-%s' % (language, country)
-
- ret_val['subdomain'] = 'www.' + google_domains.get(country.upper(), 'google.com')
- ret_val['params'] = {}
- ret_val['headers'] = {}
- if _any_language and supported_any_language:
-
- ret_val['params']['source'] = 'lnt'
- else:
-
- ret_val['headers']['Accept-Language'] = ','.join([
- lang_country,
- language + ';q=0.8,',
- 'en;q=0.6',
- '*;q=0.5',
- ])
-
-
-
-
- ret_val['params']['lr'] = "lang_" + lang_country if lang_country in lang_list else language
- ret_val['params']['hl'] = lang_country if lang_country in lang_list else language
-
-
-
-
- return ret_val
- def detect_google_sorry(resp):
- resp_url = urlparse(resp.url)
- if resp_url.netloc == 'sorry.google.com' or resp_url.path.startswith('/sorry'):
- raise SearxEngineCaptchaException()
- def request(query, params):
- """Google search request"""
- offset = (params['pageno'] - 1) * 10
- lang_info = get_lang_info(
-
- params, supported_languages, language_aliases, True
- )
- additional_parameters = {}
- if use_mobile_ui:
- additional_parameters = {
- 'asearch': 'arc',
- 'async': 'use_ac:true,_fmt:html',
- }
-
- query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
- 'q': query,
- **lang_info['params'],
- 'ie': "utf8",
- 'oe': "utf8",
- 'start': offset,
- 'filter': '0',
- 'ucbcb': 1,
- **additional_parameters,
- })
- if params['time_range'] in time_range_dict:
- query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
- if params['safesearch']:
- query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
- logger.debug("query_url --> %s", query_url)
- params['url'] = query_url
- logger.debug("HTTP header Accept-Language --> %s", lang_info.get('Accept-Language'))
- params['cookies']['CONSENT'] = "PENDING+" + str(random()*100)
- params['headers'].update(lang_info['headers'])
- if use_mobile_ui:
- params['headers']['Accept'] = '*/*'
- else:
- params['headers']['Accept'] = (
- 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
- )
- return params
- def response(resp):
- """Get response from google's search request"""
- detect_google_sorry(resp)
- results = []
-
- dom = html.fromstring(resp.text)
-
- answer_list = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]')
- if answer_list:
- answer_list = [_.xpath("normalize-space()") for _ in answer_list]
- results.append({'answer': ' '.join(answer_list)})
- else:
- logger.debug("did not find 'answer'")
-
- if not use_mobile_ui:
- try:
- _txt = eval_xpath_getindex(dom, '//div[@id="result-stats"]//text()', 0)
- _digit = ''.join([n for n in _txt if n.isdigit()])
- number_of_results = int(_digit)
- results.append({'number_of_results': number_of_results})
- except Exception as e:
- logger.debug("did not 'number_of_results'")
- logger.error(e, exc_info=True)
-
- _results_xpath = results_xpath
- if use_mobile_ui:
- _results_xpath = results_xpath_mobile_ui
- for result in eval_xpath_list(dom, _results_xpath):
-
- if extract_text(eval_xpath(result, g_section_with_header)):
- logger.debug("ignoring <g-section-with-header>")
- continue
- try:
- title_tag = eval_xpath_getindex(result, title_xpath, 0, default=None)
- if title_tag is None:
-
- logger.debug('ingoring item from the result_xpath list: missing title')
- continue
- title = extract_text(title_tag)
- url = eval_xpath_getindex(result, href_xpath, 0, None)
- if url is None:
- continue
- content = extract_text(eval_xpath_getindex(result, content_xpath, 0, default=None), allow_none=True)
- if content is None:
- logger.debug('ingoring item from the result_xpath list: missing content of title "%s"', title)
- continue
- logger.debug('add link to results: %s', title)
- results.append({
- 'url': url,
- 'title': title,
- 'content': content
- })
- except Exception as e:
- logger.error(e, exc_info=True)
- continue
-
- for suggestion in eval_xpath_list(dom, suggestion_xpath):
-
- results.append({'suggestion': extract_text(suggestion)})
- for correction in eval_xpath_list(dom, spelling_suggestion_xpath):
- results.append({'correction': extract_text(correction)})
-
- return results
- def _fetch_supported_languages(resp):
- ret_val = {}
- dom = html.fromstring(resp.text)
- radio_buttons = eval_xpath_list(dom, '//*[@id="langSec"]//input[@name="lr"]')
- for x in radio_buttons:
- name = x.get("data-name")
- code = x.get("value").split('_')[-1]
- ret_val[code] = {"name": name}
- return ret_val
|