google_images.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This is the implementation of the google images engine.
  4. .. admonition:: Content-Security-Policy (CSP)
  5. This engine needs to allow images from the `data URLs`_ (prefixed with the
  6. ``data:`` scheme)::
  7. Header set Content-Security-Policy "img-src 'self' data: ;"
  8. .. _data URLs:
  9. https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URIs
  10. """
  11. from urllib.parse import urlencode, unquote
  12. from lxml import html
  13. from searx.utils import (
  14. eval_xpath,
  15. eval_xpath_list,
  16. eval_xpath_getindex,
  17. extract_text,
  18. )
  19. from searx.engines.google import (
  20. get_lang_info,
  21. time_range_dict,
  22. detect_google_sorry,
  23. )
  24. # pylint: disable=unused-import
  25. from searx.engines.google import (
  26. supported_languages_url
  27. , _fetch_supported_languages
  28. )
  29. # pylint: enable=unused-import
  30. # about
  31. about = {
  32. "website": 'https://images.google.com',
  33. "wikidata_id": 'Q521550',
  34. "official_api_documentation": 'https://developers.google.com/custom-search',
  35. "use_official_api": False,
  36. "require_api_key": False,
  37. "results": 'HTML',
  38. }
  39. # engine dependent config
  40. categories = ['images']
  41. paging = False
  42. use_locale_domain = True
  43. time_range_support = True
  44. safesearch = True
  45. filter_mapping = {
  46. 0: 'images',
  47. 1: 'active',
  48. 2: 'active'
  49. }
  50. def scrap_out_thumbs(dom):
  51. """Scrap out thumbnail data from <script> tags.
  52. """
  53. ret_val = {}
  54. for script in eval_xpath(dom, '//script[contains(., "_setImgSrc(")]'):
  55. _script = script.text
  56. # _setImgSrc('0','data:image\/jpeg;base64,\/9j\/4AAQSkZJR ....');
  57. _thumb_no, _img_data = _script[len("_setImgSrc("):-2].split(",", 1)
  58. _thumb_no = _thumb_no.replace("'", "")
  59. _img_data = _img_data.replace("'", "")
  60. _img_data = _img_data.replace(r"\/", r"/")
  61. ret_val[_thumb_no] = _img_data.replace(r"\x3d", "=")
  62. return ret_val
  63. def scrap_img_by_id(script, data_id):
  64. """Get full image URL by data-id in parent element
  65. """
  66. img_url = ''
  67. _script = script.split('\n')
  68. for i, line in enumerate(_script):
  69. if 'gstatic.com/images' in line and data_id in line and i + 1 < len(_script):
  70. url_line = _script[i + 1]
  71. img_url = url_line.split('"')[1]
  72. img_url = unquote(img_url.replace(r'\u00', r'%'))
  73. return img_url
  74. def request(query, params):
  75. """Google-Video search request"""
  76. lang_info = get_lang_info(
  77. params, supported_languages, language_aliases, False
  78. )
  79. logger.debug(
  80. "HTTP header Accept-Language --> %s", lang_info['headers']['Accept-Language'])
  81. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  82. 'q': query,
  83. 'tbm': "isch",
  84. **lang_info['params'],
  85. 'ie': "utf8",
  86. 'oe': "utf8",
  87. 'num': 30,
  88. })
  89. if params['time_range'] in time_range_dict:
  90. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  91. if params['safesearch']:
  92. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  93. params['url'] = query_url
  94. params['headers'].update(lang_info['headers'])
  95. params['headers']['Accept'] = (
  96. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  97. )
  98. return params
  99. def response(resp):
  100. """Get response from google's search request"""
  101. results = []
  102. detect_google_sorry(resp)
  103. # convert the text to dom
  104. dom = html.fromstring(resp.text)
  105. img_bas64_map = scrap_out_thumbs(dom)
  106. img_src_script = eval_xpath_getindex(
  107. dom, '//script[contains(., "AF_initDataCallback({key: ")]', 1).text
  108. # parse results
  109. #
  110. # root element::
  111. # <div id="islmp" ..>
  112. # result div per image::
  113. # <div jsmodel="tTXmib"> / <div jsaction="..." data-id="..."
  114. # The data-id matches to a item in a json-data structure in::
  115. # <script nonce="I+vqelcy/01CKiBJi5Z1Ow">AF_initDataCallback({key: 'ds:1', ... data:function(){return [ ...
  116. # In this structure the link to the origin PNG, JPG or whatever is given
  117. # first link per image-div contains a <img> with the data-iid for bas64 encoded image data::
  118. # <img class="rg_i Q4LuWd" data-iid="0"
  119. # second link per image-div is the target link::
  120. # <a class="VFACy kGQAp" href="https://en.wikipedia.org/wiki/The_Sacrament_of_the_Last_Supper">
  121. # the second link also contains two div tags with the *description* and *publisher*::
  122. # <div class="WGvvNb">The Sacrament of the Last Supper ...</div>
  123. # <div class="fxgdke">en.wikipedia.org</div>
  124. root = eval_xpath(dom, '//div[@id="islmp"]')
  125. if not root:
  126. logger.error("did not find root element id='islmp'")
  127. return results
  128. root = root[0]
  129. for img_node in eval_xpath_list(root, './/img[contains(@class, "rg_i")]'):
  130. img_alt = eval_xpath_getindex(img_node, '@alt', 0)
  131. img_base64_id = eval_xpath(img_node, '@data-iid')
  132. if img_base64_id:
  133. img_base64_id = img_base64_id[0]
  134. thumbnail_src = img_bas64_map[img_base64_id]
  135. else:
  136. thumbnail_src = eval_xpath(img_node, '@src')
  137. if not thumbnail_src:
  138. thumbnail_src = eval_xpath(img_node, '@data-src')
  139. if thumbnail_src:
  140. thumbnail_src = thumbnail_src[0]
  141. else:
  142. thumbnail_src = ''
  143. link_node = eval_xpath_getindex(img_node, '../../../a[2]', 0)
  144. url = eval_xpath_getindex(link_node, '@href', 0, None)
  145. if url is None:
  146. logger.error("missing @href in node: %s", html.tostring(link_node))
  147. continue
  148. pub_nodes = eval_xpath(link_node, './div/div')
  149. pub_descr = img_alt
  150. pub_source = ''
  151. if pub_nodes:
  152. pub_descr = extract_text(pub_nodes[0])
  153. pub_source = extract_text(pub_nodes[1])
  154. img_src_id = eval_xpath_getindex(img_node, '../../../@data-id', 0)
  155. src_url = scrap_img_by_id(img_src_script, img_src_id)
  156. if not src_url:
  157. src_url = thumbnail_src
  158. results.append({
  159. 'url': url,
  160. 'title': img_alt,
  161. 'content': pub_descr,
  162. 'source': pub_source,
  163. 'img_src': src_url,
  164. # 'img_format': img_format,
  165. 'thumbnail_src': thumbnail_src,
  166. 'template': 'images.html'
  167. })
  168. return results