| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390 | 
import refrom flask_babel import gettextfrom lxml import html, etreefrom searx.engines.xpath import extract_text, extract_urlfrom searx import loggerfrom searx.url_utils import urlencode, urlparse, parse_qslfrom searx.utils import match_languagelogger = logger.getChild('google engine')categories = ['general']paging = Truelanguage_support = Trueuse_locale_domain = Truetime_range_support = Truedefault_hostname = 'www.google.com'country_to_hostname = {    'BG': 'www.google.bg',      'CZ': 'www.google.cz',      'DE': 'www.google.de',      'DK': 'www.google.dk',      'AT': 'www.google.at',      'CH': 'www.google.ch',      'GR': 'www.google.gr',      'AU': 'www.google.com.au',      'CA': 'www.google.ca',      'GB': 'www.google.co.uk',      'ID': 'www.google.co.id',      'IE': 'www.google.ie',      'IN': 'www.google.co.in',      'MY': 'www.google.com.my',      'NZ': 'www.google.co.nz',      'PH': 'www.google.com.ph',      'SG': 'www.google.com.sg',          'ZA': 'www.google.co.za',      'AR': 'www.google.com.ar',      'CL': 'www.google.cl',      'ES': 'www.google.es',      'MX': 'www.google.com.mx',      'EE': 'www.google.ee',      'FI': 'www.google.fi',      'BE': 'www.google.be',      'FR': 'www.google.fr',      'IL': 'www.google.co.il',      'HR': 'www.google.hr',      'HU': 'www.google.hu',      'IT': 'www.google.it',      'JP': 'www.google.co.jp',      'KR': 'www.google.co.kr',      'LT': 'www.google.lt',      'LV': 'www.google.lv',      'NO': 'www.google.no',      'NL': 'www.google.nl',      'PL': 'www.google.pl',      'BR': 'www.google.com.br',      'PT': 'www.google.pt',      'RO': 'www.google.ro',      'RU': 'www.google.ru',      'SK': 'www.google.sk',      'SI': 'www.google.si',      'SE': 'www.google.se',      'TH': 'www.google.co.th',      'TR': 'www.google.com.tr',      'UA': 'www.google.com.ua',          'HK': 'www.google.com.hk',      'TW': 'www.google.com.tw'  }url_map = 'https://www.openstreetmap.org/'\    + '?lat={latitude}&lon={longitude}&zoom={zoom}&layers=M'search_path = '/search'search_url = ('https://{hostname}' +              search_path +              '?{query}&start={offset}&gws_rd=cr&gbv=1&lr={lang}&hl={lang_short}&ei=x')time_range_search = "&tbs=qdr:{range}"time_range_dict = {'day': 'd',                   'week': 'w',                   'month': 'm',                   'year': 'y'}map_hostname_start = 'maps.google.'maps_path = '/maps'redirect_path = '/url'images_path = '/images'supported_languages_url = 'https://www.google.com/preferences?#languages'results_xpath = '//div[@class="g"]'url_xpath = './/h3/a/@href'title_xpath = './/h3'content_xpath = './/span[@class="st"]'content_misc_xpath = './/div[@class="f slp"]'suggestion_xpath = '//p[@class="_Bmc"]'spelling_suggestion_xpath = '//a[@class="spell"]'map_address_xpath = './/div[@class="s"]//table//td[2]/span/text()'map_phone_xpath = './/div[@class="s"]//table//td[2]/span/span'map_website_url_xpath = 'h3[2]/a/@href'map_website_title_xpath = 'h3[2]'map_near = 'table[@class="ts"]//tr'map_near_title = './/h4'map_near_url = './/h4/a/@href'map_near_phone = './/span[@class="nobr"]'images_xpath = './/div/a'image_url_xpath = './@href'image_img_src_xpath = './img/@src'property_address = "Address"property_phone = "Phone number"def parse_url(url_string, google_hostname):        if url_string is None:        return url_string        parsed_url = urlparse(url_string)    if (parsed_url.netloc in [google_hostname, '']            and parsed_url.path == redirect_path):        query = dict(parse_qsl(parsed_url.query))        return query['q']    else:        return url_stringdef extract_text_from_dom(result, xpath):    r = result.xpath(xpath)    if len(r) > 0:        return extract_text(r[0])    return Nonedef request(query, params):    offset = (params['pageno'] - 1) * 10    language = match_language(params['language'], supported_languages)    language_array = language.split('-')    if params['language'].find('-') > 0:        country = params['language'].split('-')[1]    elif len(language_array) == 2:        country = language_array[1]    else:        country = 'US'    url_lang = 'lang_' + language    if use_locale_domain:        google_hostname = country_to_hostname.get(country.upper(), default_hostname)    else:        google_hostname = default_hostname        params['cookies']['GOOGLE_ABUSE_EXEMPTION'] = 'x'    params['url'] = search_url.format(offset=offset,                                      query=urlencode({'q': query}),                                      hostname=google_hostname,                                      lang=url_lang,                                      lang_short=language)    if params['time_range'] in time_range_dict:        params['url'] += time_range_search.format(range=time_range_dict[params['time_range']])    params['headers']['Accept-Language'] = language + ',' + language + '-' + country    params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'    params['google_hostname'] = google_hostname    return paramsdef response(resp):    results = []        resp_url = urlparse(resp.url)    if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':        raise RuntimeWarning('sorry.google.com')    if resp_url.path.startswith('/sorry'):        raise RuntimeWarning(gettext('CAPTCHA required'))        google_hostname = resp.search_params.get('google_hostname')    google_url = "https://" + google_hostname        dom = html.fromstring(resp.text)    instant_answer = dom.xpath('//div[@id="_vBb"]//text()')    if instant_answer:        results.append({'answer': u' '.join(instant_answer)})    try:        results_num = int(dom.xpath('//div[@id="resultStats"]//text()')[0]                          .split()[1].replace(',', ''))        results.append({'number_of_results': results_num})    except:        pass        for result in dom.xpath(results_xpath):        try:            title = extract_text(result.xpath(title_xpath)[0])            url = parse_url(extract_url(result.xpath(url_xpath), google_url), google_hostname)            parsed_url = urlparse(url, google_hostname)                        if parsed_url.netloc == google_hostname:                                continue                                                                                                                                                                                                                                                                                                                            else:                                content = extract_text_from_dom(result, content_xpath)                if content is None:                    continue                content_misc = extract_text_from_dom(result, content_misc_xpath)                if content_misc is not None:                    content = content_misc + "<br />" + content                                results.append({'url': url,                                'title': title,                                'content': content                                })        except:            logger.debug('result parse error in:\n%s', etree.tostring(result, pretty_print=True))            continue        for suggestion in dom.xpath(suggestion_xpath):                results.append({'suggestion': extract_text(suggestion)})    for correction in dom.xpath(spelling_suggestion_xpath):        results.append({'correction': extract_text(correction)})        return resultsdef parse_images(result, google_hostname):    results = []    for image in result.xpath(images_xpath):        url = parse_url(extract_text(image.xpath(image_url_xpath)[0]), google_hostname)        img_src = extract_text(image.xpath(image_img_src_xpath)[0])                results.append({'url': url,                        'title': '',                        'content': '',                        'img_src': img_src,                        'template': 'images.html'                        })    return resultsdef parse_map_near(parsed_url, x, google_hostname):    results = []    for result in x:        title = extract_text_from_dom(result, map_near_title)        url = parse_url(extract_text_from_dom(result, map_near_url), google_hostname)        attributes = []        phone = extract_text_from_dom(result, map_near_phone)        add_attributes(attributes, property_phone, phone, 'tel:' + phone)        results.append({'title': title,                        'url': url,                        'content': attributes_to_html(attributes)                        })    return resultsdef parse_map_detail(parsed_url, result, google_hostname):    results = []        m = re.search(r'@([0-9\.]+),([0-9\.]+),([0-9]+)', parsed_url.path)    if m is None:        m = re.search(r'll\=([0-9\.]+),([0-9\.]+)\&z\=([0-9]+)', parsed_url.query)    if m is not None:                lon = float(m.group(2))          lat = float(m.group(1))          zoom = int(m.group(3))                  attributes = []        address = extract_text_from_dom(result, map_address_xpath)        phone = extract_text_from_dom(result, map_phone_xpath)        add_attributes(attributes, property_address, address, 'geo:' + str(lat) + ',' + str(lon))        add_attributes(attributes, property_phone, phone, 'tel:' + phone)                website_title = extract_text_from_dom(result, map_website_title_xpath)        content = extract_text_from_dom(result, content_xpath)        website_url = parse_url(extract_text_from_dom(result, map_website_url_xpath), google_hostname)                if website_url is not None:            results.append({'title': website_title,                            'content': (content + '<br />' if content is not None else '')                            + attributes_to_html(attributes),                            'url': website_url                            })    return resultsdef add_attributes(attributes, name, value, url):    if value is not None and len(value) > 0:        attributes.append({'label': name, 'value': value, 'url': url})def attributes_to_html(attributes):    retval = '<table class="table table-striped">'    for a in attributes:        value = a.get('value')        if 'url' in a:            value = '<a href="' + a.get('url') + '">' + value + '</a>'        retval = retval + '<tr><th>' + a.get('label') + '</th><td>' + value + '</td></tr>'    retval = retval + '</table>'    return retvaldef _fetch_supported_languages(resp):    supported_languages = {}    dom = html.fromstring(resp.text)    options = dom.xpath('//table//td/font/label/span')    for option in options:        code = option.xpath('./@id')[0][1:]        name = option.text.title()        supported_languages[code] = {"name": name}    return supported_languages
 |