google_images.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """Google (Images)
  3. :website: https://images.google.com (redirected to subdomain www.)
  4. :provide-api: yes (https://developers.google.com/custom-search/)
  5. :using-api: not the offical, since it needs registration to another service
  6. :results: HTML
  7. :stable: no
  8. :template: images.html
  9. :parse: url, title, content, source, thumbnail_src, img_src
  10. For detailed description of the *REST-full* API see: `Query Parameter
  11. Definitions`_.
  12. .. _admonition:: Content-Security-Policy (CSP)
  13. This engine needs to allow images from the `data URLs`_ (prefixed with the
  14. ``data:` scheme).::
  15. Header set Content-Security-Policy "img-src 'self' data: ;"
  16. .. _Query Parameter Definitions:
  17. https://developers.google.com/custom-search/docs/xml_results#WebSearch_Query_Parameter_Definitions
  18. """
  19. from urllib.parse import urlencode, urlparse, unquote
  20. from lxml import html
  21. from flask_babel import gettext
  22. from searx import logger
  23. from searx.utils import extract_text, eval_xpath
  24. from searx.engines.google import _fetch_supported_languages, supported_languages_url # NOQA # pylint: disable=unused-import
  25. from searx.engines.google import (
  26. get_lang_country,
  27. google_domains,
  28. time_range_dict,
  29. )
  30. logger = logger.getChild('google images')
  31. # engine dependent config
  32. categories = ['images']
  33. paging = False
  34. language_support = True
  35. use_locale_domain = True
  36. time_range_support = True
  37. safesearch = True
  38. filter_mapping = {
  39. 0: 'images',
  40. 1: 'active',
  41. 2: 'active'
  42. }
  43. def scrap_out_thumbs(dom):
  44. """Scrap out thumbnail data from <script> tags.
  45. """
  46. ret_val = dict()
  47. for script in eval_xpath(dom, '//script[contains(., "_setImgSrc(")]'):
  48. _script = script.text
  49. # _setImgSrc('0','data:image\/jpeg;base64,\/9j\/4AAQSkZJR ....');
  50. _thumb_no, _img_data = _script[len("_setImgSrc("):-2].split(",", 1)
  51. _thumb_no = _thumb_no.replace("'", "")
  52. _img_data = _img_data.replace("'", "")
  53. _img_data = _img_data.replace(r"\/", r"/")
  54. ret_val[_thumb_no] = _img_data.replace(r"\x3d", "=")
  55. return ret_val
  56. def scrap_img_by_id(script, data_id):
  57. """Get full image URL by data-id in parent element
  58. """
  59. img_url = ''
  60. _script = script.split('\n')
  61. for i, line in enumerate(_script):
  62. if 'gstatic.com/images' in line and data_id in line:
  63. url_line = _script[i + 1]
  64. img_url = url_line.split('"')[1]
  65. img_url = unquote(img_url.replace(r'\u00', r'%'))
  66. return img_url
  67. def request(query, params):
  68. """Google-Video search request"""
  69. language, country, lang_country = get_lang_country(
  70. # pylint: disable=undefined-variable
  71. params, supported_languages, language_aliases
  72. )
  73. subdomain = 'www.' + google_domains.get(country.upper(), 'google.com')
  74. query_url = 'https://' + subdomain + '/search' + "?" + urlencode({
  75. 'q': query,
  76. 'tbm': "isch",
  77. 'hl': lang_country,
  78. 'lr': "lang_" + language,
  79. 'ie': "utf8",
  80. 'oe': "utf8",
  81. 'num': 30,
  82. })
  83. if params['time_range'] in time_range_dict:
  84. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  85. if params['safesearch']:
  86. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  87. params['url'] = query_url
  88. logger.debug("query_url --> %s", query_url)
  89. params['headers']['Accept-Language'] = (
  90. "%s,%s;q=0.8,%s;q=0.5" % (lang_country, language, language))
  91. logger.debug(
  92. "HTTP Accept-Language --> %s", params['headers']['Accept-Language'])
  93. params['headers']['Accept'] = (
  94. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  95. )
  96. # params['google_subdomain'] = subdomain
  97. return params
  98. def response(resp):
  99. """Get response from google's search request"""
  100. results = []
  101. # detect google sorry
  102. resp_url = urlparse(resp.url)
  103. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  104. raise RuntimeWarning('sorry.google.com')
  105. if resp_url.path.startswith('/sorry'):
  106. raise RuntimeWarning(gettext('CAPTCHA required'))
  107. # which subdomain ?
  108. # subdomain = resp.search_params.get('google_subdomain')
  109. # convert the text to dom
  110. dom = html.fromstring(resp.text)
  111. img_bas64_map = scrap_out_thumbs(dom)
  112. img_src_script = eval_xpath(dom, '//script[contains(., "AF_initDataCallback({key: ")]')[1].text
  113. # parse results
  114. #
  115. # root element::
  116. # <div id="islmp" ..>
  117. # result div per image::
  118. # <div jsmodel="tTXmib"> / <div jsaction="..." data-id="..."
  119. # The data-id matches to a item in a json-data structure in::
  120. # <script nonce="I+vqelcy/01CKiBJi5Z1Ow">AF_initDataCallback({key: 'ds:1', ... data:function(){return [ ...
  121. # In this structure the link to the origin PNG, JPG or whatever is given
  122. # first link per image-div contains a <img> with the data-iid for bas64 encoded image data::
  123. # <img class="rg_i Q4LuWd" data-iid="0"
  124. # second link per image-div is the target link::
  125. # <a class="VFACy kGQAp" href="https://en.wikipedia.org/wiki/The_Sacrament_of_the_Last_Supper">
  126. # the second link also contains two div tags with the *description* and *publisher*::
  127. # <div class="WGvvNb">The Sacrament of the Last Supper ...</div>
  128. # <div class="fxgdke">en.wikipedia.org</div>
  129. root = eval_xpath(dom, '//div[@id="islmp"]')
  130. if not root:
  131. logger.error("did not find root element id='islmp'")
  132. return results
  133. root = root[0]
  134. for img_node in eval_xpath(root, './/img[contains(@class, "rg_i")]'):
  135. try:
  136. img_alt = eval_xpath(img_node, '@alt')[0]
  137. img_base64_id = eval_xpath(img_node, '@data-iid')
  138. if img_base64_id:
  139. img_base64_id = img_base64_id[0]
  140. thumbnail_src = img_bas64_map[img_base64_id]
  141. else:
  142. thumbnail_src = eval_xpath(img_node, '@src')
  143. if not thumbnail_src:
  144. thumbnail_src = eval_xpath(img_node, '@data-src')
  145. if thumbnail_src:
  146. thumbnail_src = thumbnail_src[0]
  147. else:
  148. thumbnail_src = ''
  149. link_node = eval_xpath(img_node, '../../../a[2]')[0]
  150. url = eval_xpath(link_node, '@href')[0]
  151. pub_nodes = eval_xpath(link_node, './div/div')
  152. pub_descr = img_alt
  153. pub_source = ''
  154. if pub_nodes:
  155. pub_descr = extract_text(pub_nodes[0])
  156. pub_source = extract_text(pub_nodes[1])
  157. img_src_id = eval_xpath(img_node, '../../../@data-id')[0]
  158. src_url = scrap_img_by_id(img_src_script, img_src_id)
  159. if not src_url:
  160. src_url = thumbnail_src
  161. results.append({
  162. 'url': url,
  163. 'title': img_alt,
  164. 'content': pub_descr,
  165. 'source': pub_source,
  166. 'img_src': src_url,
  167. # 'img_format': img_format,
  168. 'thumbnail_src': thumbnail_src,
  169. 'template': 'images.html'
  170. })
  171. except Exception as e: # pylint: disable=broad-except
  172. logger.error(e, exc_info=True)
  173. # from lxml import etree
  174. # logger.debug(etree.tostring(img_node, pretty_print=True))
  175. # import pdb
  176. # pdb.set_trace()
  177. continue
  178. return results