@@ -1,210 +1,207 @@
1−# Google (Web)
2−#
3−# @website https://www.google.com
4−# @provide-api yes (https://developers.google.com/custom-search/)
5−#
6−# @using-api no
7−# @results HTML
8−# @stable no (HTML can change)
9−# @parse url, title, content, suggestion
10−
11−import re
1+# SPDX-License-Identifier: AGPL-3.0-or-later
2+"""Google (Web)
3+
4+:website: https://www.google.com
5+:provide-api: yes (https://developers.google.com/custom-search/)
6+:using-api: not the offical, since it needs registration to another service
7+:results: HTML
8+:stable: no
9+:parse: url, title, content, number_of_results, answer, suggestion, correction
10+
11+For detailed description of the *REST-full* API see: `Query Parameter
12+Definitions`_.
13+
14+.. _Query Parameter Definitions:
15+ https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
16+
17+"""
18+
19+# pylint: disable=invalid-name, missing-function-docstring
20+
21+from lxml import html
1222from flask_babel import gettext
13−from lxml import html, etree
14−from searx.engines.xpath import extract_text, extract_url
23+from searx.engines.xpath import extract_text
1524from searx import logger
16−from searx.url_utils import urlencode, urlparse, parse_qsl
25+from searx.url_utils import urlencode, urlparse
1726from searx.utils import match_language, eval_xpath
1827
1928logger = logger.getChild('google engine')
2029
21−
2230# engine dependent config
2331categories = ['general']
2432paging = True
2533language_support = True
26−use_locale_domain = True
2734time_range_support = True
35+safesearch = True
36+supported_languages_url = 'https://www.google.com/preferences?#languages'
2837
2938# based on https://en.wikipedia.org/wiki/List_of_Google_domains and tests
30−default_hostname = 'www.google.com'
31−
32−country_to_hostname = {
33− 'BG': 'www.google.bg', # Bulgaria
34− 'CZ': 'www.google.cz', # Czech Republic
35− 'DE': 'www.google.de', # Germany
36− 'DK': 'www.google.dk', # Denmark
37− 'AT': 'www.google.at', # Austria
38− 'CH': 'www.google.ch', # Switzerland
39− 'GR': 'www.google.gr', # Greece
40− 'AU': 'www.google.com.au', # Australia
41− 'CA': 'www.google.ca', # Canada
42− 'GB': 'www.google.co.uk', # United Kingdom
43− 'ID': 'www.google.co.id', # Indonesia
44− 'IE': 'www.google.ie', # Ireland
45− 'IN': 'www.google.co.in', # India
46− 'MY': 'www.google.com.my', # Malaysia
47− 'NZ': 'www.google.co.nz', # New Zealand
48− 'PH': 'www.google.com.ph', # Philippines
49− 'SG': 'www.google.com.sg', # Singapore
50− # 'US': 'www.google.us', # United States, redirect to .com
51− 'ZA': 'www.google.co.za', # South Africa
52− 'AR': 'www.google.com.ar', # Argentina
53− 'CL': 'www.google.cl', # Chile
54− 'ES': 'www.google.es', # Spain
55− 'MX': 'www.google.com.mx', # Mexico
56− 'EE': 'www.google.ee', # Estonia
57− 'FI': 'www.google.fi', # Finland
58− 'BE': 'www.google.be', # Belgium
59− 'FR': 'www.google.fr', # France
60− 'IL': 'www.google.co.il', # Israel
61− 'HR': 'www.google.hr', # Croatia
62− 'HU': 'www.google.hu', # Hungary
63− 'IT': 'www.google.it', # Italy
64− 'JP': 'www.google.co.jp', # Japan
65− 'KR': 'www.google.co.kr', # South Korea
66− 'LT': 'www.google.lt', # Lithuania
67− 'LV': 'www.google.lv', # Latvia
68− 'NO': 'www.google.no', # Norway
69− 'NL': 'www.google.nl', # Netherlands
70− 'PL': 'www.google.pl', # Poland
71− 'BR': 'www.google.com.br', # Brazil
72− 'PT': 'www.google.pt', # Portugal
73− 'RO': 'www.google.ro', # Romania
74− 'RU': 'www.google.ru', # Russia
75− 'SK': 'www.google.sk', # Slovakia
76− 'SI': 'www.google.si', # Slovenia
77− 'SE': 'www.google.se', # Sweden
78− 'TH': 'www.google.co.th', # Thailand
79− 'TR': 'www.google.com.tr', # Turkey
80− 'UA': 'www.google.com.ua', # Ukraine
81− # 'CN': 'www.google.cn', # China, only from China ?
82− 'HK': 'www.google.com.hk', # Hong Kong
83− 'TW': 'www.google.com.tw' # Taiwan
39+google_domains = {
40+ 'BG': 'google.bg', # Bulgaria
41+ 'CZ': 'google.cz', # Czech Republic
42+ 'DE': 'google.de', # Germany
43+ 'DK': 'google.dk', # Denmark
44+ 'AT': 'google.at', # Austria
45+ 'CH': 'google.ch', # Switzerland
46+ 'GR': 'google.gr', # Greece
47+ 'AU': 'google.com.au', # Australia
48+ 'CA': 'google.ca', # Canada
49+ 'GB': 'google.co.uk', # United Kingdom
50+ 'ID': 'google.co.id', # Indonesia
51+ 'IE': 'google.ie', # Ireland
52+ 'IN': 'google.co.in', # India
53+ 'MY': 'google.com.my', # Malaysia
54+ 'NZ': 'google.co.nz', # New Zealand
55+ 'PH': 'google.com.ph', # Philippines
56+ 'SG': 'google.com.sg', # Singapore
57+ # 'US': 'google.us', # United States, redirect to .com
58+ 'ZA': 'google.co.za', # South Africa
59+ 'AR': 'google.com.ar', # Argentina
60+ 'CL': 'google.cl', # Chile
61+ 'ES': 'google.es', # Spain
62+ 'MX': 'google.com.mx', # Mexico
63+ 'EE': 'google.ee', # Estonia
64+ 'FI': 'google.fi', # Finland
65+ 'BE': 'google.be', # Belgium
66+ 'FR': 'google.fr', # France
67+ 'IL': 'google.co.il', # Israel
68+ 'HR': 'google.hr', # Croatia
69+ 'HU': 'google.hu', # Hungary
70+ 'IT': 'google.it', # Italy
71+ 'JP': 'google.co.jp', # Japan
72+ 'KR': 'google.co.kr', # South Korea
73+ 'LT': 'google.lt', # Lithuania
74+ 'LV': 'google.lv', # Latvia
75+ 'NO': 'google.no', # Norway
76+ 'NL': 'google.nl', # Netherlands
77+ 'PL': 'google.pl', # Poland
78+ 'BR': 'google.com.br', # Brazil
79+ 'PT': 'google.pt', # Portugal
80+ 'RO': 'google.ro', # Romania
81+ 'RU': 'google.ru', # Russia
82+ 'SK': 'google.sk', # Slovakia
83+ 'SI': 'google.si', # Slovenia
84+ 'SE': 'google.se', # Sweden
85+ 'TH': 'google.co.th', # Thailand
86+ 'TR': 'google.com.tr', # Turkey
87+ 'UA': 'google.com.ua', # Ukraine
88+ # 'CN': 'google.cn', # China, only from China ?
89+ 'HK': 'google.com.hk', # Hong Kong
90+ 'TW': 'google.com.tw' # Taiwan
8491}
8592
86−# osm
87−url_map = 'https://www.openstreetmap.org/'\
88− + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'
89−
90−# search-url
91−search_path = '/search'
92−search_url = ('https://{hostname}' +
93− search_path +
94− '?{query}&start={offset}&gws_rd=cr&gbv=1&lr={lang}&hl={lang_short}&ei=x')
95−
96−time_range_search = "&tbs=qdr:{range}"
97−time_range_dict = {'day': 'd',
98− 'week': 'w',
99− 'month': 'm',
100− 'year': 'y'}
101−
102−# other URLs
103−map_hostname_start = 'maps.google.'
104−maps_path = '/maps'
105−redirect_path = '/url'
106−images_path = '/images'
107−supported_languages_url = 'https://www.google.com/preferences?#languages'
93+time_range_dict = {
94+ 'day': 'd',
95+ 'week': 'w',
96+ 'month': 'm',
97+ 'year': 'y'
98+}
99+
100+# Filter results. 0: None, 1: Moderate, 2: Strict
101+filter_mapping = {
102+ 0 : 'off',
103+ 1 : 'medium',
104+ 2 : 'high'
105+}
108106
109107# specific xpath variables
110−results_xpath = '//div[contains(@class, "ZINbbc")]'
111−url_xpath = './/div[@class="kCrYT"][1]/a/@href'
112−title_xpath = './/div[@class="kCrYT"][1]/a/div[1]'
113−content_xpath = './/div[@class="kCrYT"][2]//div[contains(@class, "BNeawe")]//div[contains(@class, "BNeawe")]'
114−suggestion_xpath = '//div[contains(@class, "ZINbbc")][last()]//div[@class="rVLSBd"]/a//div[contains(@class, "BNeawe")]'
115−spelling_suggestion_xpath = '//div[@id="scc"]//a'
116−
117−# map : detail location
118−map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()'
119−map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span'
120−map_website_url_xpath = 'h3[2]/a/@href'
121−map_website_title_xpath = 'h3[2]'
122−
123−# map : near the location
124−map_near = 'table[@class="ts"]//tr'
125−map_near_title = './/h4'
126−map_near_url = './/h4/a/@href'
127−map_near_phone = './/span[@class="nobr"]'
128−
129−# images
130−images_xpath = './/div/a'
131−image_url_xpath = './@href'
132−image_img_src_xpath = './img/@src'
133−
134−# property names
135−# FIXME : no translation
136−property_address = "Address"
137−property_phone = "Phone number"
138−
139−
140−# remove google-specific tracking-url
141−def parse_url(url_string, google_hostname):
142− # sanity check
143− if url_string is None:
144− return url_string
145−
146− # normal case
147− parsed_url = urlparse(url_string)
148− if (parsed_url.netloc in [google_hostname, '']
149− and parsed_url.path == redirect_path):
150− query = dict(parse_qsl(parsed_url.query))
151− return query['q']
152− else:
153− return url_string
108+# ------------------------
109+
110+# google results are grouped into <div class="g" ../>
111+results_xpath = '//div[@class="g"]'
112+
113+# google *sections* are no usual *results*, we ignore them
114+g_section_with_header='./g-section-with-header'
115+
116+# the title is a h3 tag relative to the result group
117+title_xpath = './/h3[1]'
154118
119+# in the result group there is <div class="r" ../> it's first child is a <a
120+# href=...> (on some results, the <a> is the first "descendant", not ""child")
121+href_xpath = './/div[@class="r"]//a/@href'
122+
123+# in the result group there is <div class="s" ../> containing he *content*
124+content_xpath = './/div[@class="s"]'
125+
126+# Suggestions are links placed in a *card-section*, we extract only the text
127+# from the links not the links itself.
128+suggestion_xpath = '//div[contains(@class, "card-section")]//a'
129+
130+# Since google does *auto-correction* on the first query these are not really
131+# *spelling suggestions*, we use them anyway.
132+spelling_suggestion_xpath = '//div[@class="med"]/p/a'
155133
156−# returns extract_text on the first result selected by the xpath or None
157134def extract_text_from_dom(result, xpath):
135+ """returns extract_text on the first result selected by the xpath or None"""
158136 r = eval_xpath(result, xpath)
159137 if len(r) > 0:
160138 return extract_text(r[0])
161139 return None
162140
163−
164−# do search-request
165−def request(query, params):
166− offset = (params['pageno'] - 1) * 10
167−
168− if params['language'] == 'all' or params['language'] == 'en-US':
169− language = 'en-GB'
170− else:
171− language = match_language(params['language'], supported_languages, language_aliases)
141+def get_lang_country(params, lang_list, custom_aliases):
142+ """Returns a tuple with *langauage* on its first and *country* on its second
143+ position."""
144+ language = params['language']
145+ if language == 'all':
146+ language = 'en-US'
172147
173148 language_array = language.split('-')
174− if params['language'].find('-') > 0:
175− country = params['language'].split('-')[1]
176− elif len(language_array) == 2:
149+
150+ if len(language_array) == 2:
177151 country = language_array[1]
178152 else:
179− country = 'US'
153+ country = language_array[0].upper()
180154
181− url_lang = 'lang_' + language
155+ language = match_language(language, lang_list, custom_aliases)
156+ lang_country = '%s-%s' % (language, country)
157+ if lang_country == 'en-EN':
158+ lang_country = 'en'
182159
183− if use_locale_domain:
184− google_hostname = country_to_hostname.get(country.upper(), default_hostname)
185− else:
186− google_hostname = default_hostname
187−
188− # original format: ID=3e2b6616cee08557:TM=5556667580:C=r:IP=4.1.12.5-:S=23ASdf0soFgF2d34dfgf-_22JJOmHdfgg
189− params['cookies']['GOOGLE_ABUSE_EXEMPTION'] = 'x'
190− params['url'] = search_url.format(offset=offset,
191− query=urlencode({'q': query}),
192− hostname=google_hostname,
193− lang=url_lang,
194− lang_short=language)
195− if params['time_range'] in time_range_dict:
196− params['url'] += time_range_search.format(range=time_range_dict[params['time_range']])
160+ return language, country, lang_country
197161
198− params['headers']['Accept-Language'] = language + ',' + language + '-' + country
199− params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
162+def request(query, params):
163+ """Google search request"""
200164
201− params['google_hostname'] = google_hostname
165+ offset = (params['pageno'] - 1) * 10
166+ language, country, lang_country = get_lang_country(
167+ # pylint: disable=undefined-variable
168+ params, supported_languages, language_aliases
169+ )
170+ subdomain = 'www.' + google_domains.get(country.upper(), 'google.com')
171+
172+ # https://www.google.de/search?q=corona&hl=de-DE&lr=lang_de&start=0&tbs=qdr%3Ad&safe=medium
173+ query_url = 'https://'+ subdomain + '/search' + "?" + urlencode({
174+ 'q': query,
175+ 'hl': lang_country,
176+ 'lr': "lang_" + language,
177+ 'ie': "utf8",
178+ 'oe': "utf8",
179+ 'start': offset,
180+ })
202181
203− return params
182+ if params['time_range'] in time_range_dict:
183+ query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
184+ if params['safesearch']:
185+ query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
186+
187+ params['url'] = query_url
188+ logger.debug("query_url --> %s", query_url)
189+
190+ # en-US,en;q=0.8,en;q=0.5
191+ params['headers']['Accept-Language'] = (
192+ lang_country + ',' + language + ';q=0.8,' + language + ';q=0.5'
193+ )
194+ logger.debug("HTTP header Accept-Language --> %s",
195+ params['headers']['Accept-Language'])
196+ params['headers']['Accept'] = (
197+ 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
198+ )
199+ #params['google_subdomain'] = subdomain
204200
201+ return params
205202
206−# get response from search-request
207203def response(resp):
204+ """Get response from google's search request"""
208205 results = []
209206
210207 # detect google sorry
@@ -215,68 +212,53 @@ def response(resp):
215212 if resp_url.path.startswith('/sorry'):
216213 raise RuntimeWarning(gettext('CAPTCHA required'))
217214
218− # which hostname ?
219− google_hostname = resp.search_params.get('google_hostname')
220− google_url = "https://" + google_hostname
215+ # which subdomain ?
216+ # subdomain = resp.search_params.get('google_subdomain')
221217
222218 # convert the text to dom
223219 dom = html.fromstring(resp.text)
224220
225− instant_answer = eval_xpath(dom, '//div[@id="_vBb"]//text()')
226− if instant_answer:
227− results.append({'answer': u' '.join(instant_answer)})
221+ # results --> answer
222+ answer = eval_xpath(dom, '//div[contains(@class, "LGOjhe")]//text()')
223+ if answer:
224+ results.append({'answer': ' '.join(answer)})
225+ else:
226+ logger.debug("did not found 'answer'")
227+
228+ # results --> number_of_results
228229 try:
229− results_num = int(eval_xpath(dom, '//div[@id="resultStats"]//text()')[0]
230− .split()[1].replace(',', ''))
231− results.append({'number_of_results': results_num})
232− except:
233− pass
230+ _txt = eval_xpath(dom, '//div[@id="result-stats"]//text()')[0]
231+ _digit = ''.join([n for n in _txt if n.isdigit()])
232+ number_of_results = int(_digit)
233+ results.append({'number_of_results': number_of_results})
234+
235+ except Exception as e: # pylint: disable=broad-except
236+ logger.debug("did not 'number_of_results'")
237+ logger.error(e, exc_info=True)
234238
235239 # parse results
236240 for result in eval_xpath(dom, results_xpath):
241+
242+ # google *sections*
243+ if extract_text(eval_xpath(result, g_section_with_header)):
244+ logger.debug("ingoring <g-section-with-header>")
245+ continue
246+
237247 try:
238248 title = extract_text(eval_xpath(result, title_xpath)[0])
239− url = parse_url(extract_url(eval_xpath(result, url_xpath), google_url), google_hostname)
240− parsed_url = urlparse(url, google_hostname)
241−
242− # map result
243− if parsed_url.netloc == google_hostname:
244− # TODO fix inside links
245− continue
246− # if parsed_url.path.startswith(maps_path) or parsed_url.netloc.startswith(map_hostname_start):
247− # print "yooooo"*30
248− # x = eval_xpath(result, map_near)
249− # if len(x) > 0:
250− # # map : near the location
251− # results = results + parse_map_near(parsed_url, x, google_hostname)
252− # else:
253− # # map : detail about a location
254− # results = results + parse_map_detail(parsed_url, result, google_hostname)
255− # # google news
256− # elif parsed_url.path == search_path:
257− # # skipping news results
258− # pass
259−
260− # # images result
261− # elif parsed_url.path == images_path:
262− # # only thumbnail image provided,
263− # # so skipping image results
264− # # results = results + parse_images(result, google_hostname)
265− # pass
266−
267− else:
268− # normal result
269− content = extract_text_from_dom(result, content_xpath)
270− if content is None:
271− continue
272−
273− # append result
274− results.append({'url': url,
275− 'title': title,
276− 'content': content
277− })
278− except:
279− logger.debug('result parse error in:\n%s', etree.tostring(result, pretty_print=True))
249+ url = eval_xpath(result, href_xpath)[0]
250+ content = extract_text_from_dom(result, content_xpath)
251+ results.append({
252+ 'url': url,
253+ 'title': title,
254+ 'content': content
255+ })
256+ except Exception as e: # pylint: disable=broad-except
257+ logger.error(e, exc_info=True)
258+ #from lxml import etree
259+ #logger.debug(etree.tostring(result, pretty_print=True))
260+ #import pdb
261+ #pdb.set_trace()
280262 continue
281263
282264 # parse suggestion
@@ -290,102 +272,16 @@ def response(resp):
290272 # return results
291273 return results
292274
293−
294−def parse_images(result, google_hostname):
295− results = []
296− for image in eval_xpath(result, images_xpath):
297− url = parse_url(extract_text(eval_xpath(image, image_url_xpath)[0]), google_hostname)
298− img_src = extract_text(eval_xpath(image, image_img_src_xpath)[0])
299−
300− # append result
301− results.append({'url': url,
302− 'title': '',
303− 'content': '',
304− 'img_src': img_src,
305− 'template': 'images.html'
306− })
307−
308− return results
309−
310−
311−def parse_map_near(parsed_url, x, google_hostname):
312− results = []
313−
314− for result in x:
315− title = extract_text_from_dom(result, map_near_title)
316− url = parse_url(extract_text_from_dom(result, map_near_url), google_hostname)
317− attributes = []
318− phone = extract_text_from_dom(result, map_near_phone)
319− add_attributes(attributes, property_phone, phone, 'tel:' + phone)
320− results.append({'title': title,
321− 'url': url,
322− 'content': attributes_to_html(attributes)
323− })
324−
325− return results
326−
327−
328−def parse_map_detail(parsed_url, result, google_hostname):
329− results = []
330−
331− # try to parse the geoloc
332− m = re.search(r'@([0-9\.]+),([0-9\.]+),([0-9]+)', parsed_url.path)
333− if m is None:
334− m = re.search(r'll\=([0-9\.]+),([0-9\.]+)\&z\=([0-9]+)', parsed_url.query)
335−
336− if m is not None:
337− # geoloc found (ignored)
338− lon = float(m.group(2)) # noqa
339− lat = float(m.group(1)) # noqa
340− zoom = int(m.group(3)) # noqa
341−
342− # attributes
343− attributes = []
344− address = extract_text_from_dom(result, map_address_xpath)
345− phone = extract_text_from_dom(result, map_phone_xpath)
346− add_attributes(attributes, property_address, address, 'geo:' + str(lat) + ',' + str(lon))
347− add_attributes(attributes, property_phone, phone, 'tel:' + phone)
348−
349− # title / content / url
350− website_title = extract_text_from_dom(result, map_website_title_xpath)
351− content = extract_text_from_dom(result, content_xpath)
352− website_url = parse_url(extract_text_from_dom(result, map_website_url_xpath), google_hostname)
353−
354− # add a result if there is a website
355− if website_url is not None:
356− results.append({'title': website_title,
357− 'content': (content + '<br />' if content is not None else '')
358− + attributes_to_html(attributes),
359− 'url': website_url
360− })
361−
362− return results
363−
364−
365−def add_attributes(attributes, name, value, url):
366− if value is not None and len(value) > 0:
367− attributes.append({'label': name, 'value': value, 'url': url})
368−
369−
370−def attributes_to_html(attributes):
371− retval = '<table class="table table-striped">'
372− for a in attributes:
373− value = a.get('value')
374− if 'url' in a:
375− value = '<a href="' + a.get('url') + '">' + value + '</a>'
376− retval = retval + '<tr><th>' + a.get('label') + '</th><td>' + value + '</td></tr>'
377− retval = retval + '</table>'
378− return retval
379−
380−
381275# get supported languages from their site
382276def _fetch_supported_languages(resp):
383− supported_languages = {}
277+ ret_val = {}
384278 dom = html.fromstring(resp.text)
385− options = eval_xpath(dom, '//*[@id="langSec"]//input[@name="lr"]')
386− for option in options:
387− code = eval_xpath(option, './@value')[0].split('_')[-1]
388− name = eval_xpath(option, './@data-name')[0].title()
389− supported_languages[code] = {"name": name}
390279
391− return supported_languages
280+ radio_buttons = eval_xpath(dom, '//*[@id="langSec"]//input[@name="lang"]')
281+
282+ for x in radio_buttons:
283+ name = x.get("data-name")
284+ code = x.get("value")
285+ ret_val[code] = {"name": name}
286+
287+ return ret_val