google_images.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. import re
  12. from urllib.parse import urlencode, unquote
  13. from lxml import html
  14. from searx.utils import (
  15. eval_xpath,
  16. eval_xpath_list,
  17. eval_xpath_getindex,
  18. extract_text,
  19. )
  20. from searx.engines.google import (
  21. get_lang_info,
  22. time_range_dict,
  23. detect_google_sorry,
  24. )
  25. # pylint: disable=unused-import
  26. from searx.engines.google import supported_languages_url, _fetch_supported_languages
  27. # pylint: enable=unused-import
  28. # about
  29. about = {
  30. "website": 'https://images.google.com',
  31. "wikidata_id": 'Q521550',
  32. "official_api_documentation": 'https://developers.google.com/custom-search',
  33. "use_official_api": False,
  34. "require_api_key": False,
  35. "results": 'HTML',
  36. }
  37. # engine dependent config
  38. categories = ['images', 'web']
  39. paging = False
  40. use_locale_domain = True
  41. time_range_support = True
  42. safesearch = True
  43. send_accept_language_header = True
  44. filter_mapping = {0: 'images', 1: 'active', 2: 'active'}
  45. def scrap_out_thumbs(dom):
  46. """Scrap out thumbnail data from <script> tags."""
  47. ret_val = {}
  48. for script in eval_xpath(dom, '//script[contains(., "_setImgSrc(")]'):
  49. _script = script.text
  50. # _setImgSrc('0','data:image\/jpeg;base64,\/9j\/4AAQSkZJR ....');
  51. _thumb_no, _img_data = _script[len("_setImgSrc(") : -2].split(",", 1)
  52. _thumb_no = _thumb_no.replace("'", "")
  53. _img_data = _img_data.replace("'", "")
  54. _img_data = _img_data.replace(r"\/", r"/")
  55. ret_val[_thumb_no] = _img_data.replace(r"\x3d", "=")
  56. return ret_val
  57. # [0, "-H96xjSoW5DsgM", ["https://encrypted-tbn0.gstatic.com/images?q...", 155, 324]
  58. # , ["https://assets.cdn.moviepilot.de/files/d3bf..", 576, 1200],
  59. _RE_JS_IMAGE_URL = re.compile(
  60. r'"'
  61. r'([^"]*)' # -H96xjSoW5DsgM
  62. r'",\s*\["'
  63. r'https://[^\.]*\.gstatic.com/images[^"]*' # https://encrypted-tbn0.gstatic.com/images?q...
  64. r'[^\[]*\["'
  65. r'(https?://[^"]*)' # https://assets.cdn.moviepilot.de/files/d3bf...
  66. )
  67. def parse_urls_img_from_js(dom):
  68. # There are two HTML script tags starting with a JS function
  69. # 'AF_initDataCallback(...)'
  70. #
  71. # <script nonce="zscm+Ab/JzBk1Qd4GY6wGQ">
  72. # AF_initDataCallback({key: 'ds:0', hash: '1', data:[], sideChannel: {}});
  73. # </script>
  74. # <script nonce="zscm+Ab/JzBk1Qd4GY6wGQ">
  75. # AF_initDataCallback({key: 'ds:1', hash: '2', data:[null,[[["online_chips",[["the big",
  76. # ["https://encrypted-tbn0.gstatic.com/images?q...",null,null,true,[null,0],f
  77. # ...
  78. # </script>
  79. #
  80. # The second script contains the URLs of the images.
  81. # The AF_initDataCallback(..) is called with very large dictionary, that
  82. # looks like JSON but it is not JSON since it contains JS variables and
  83. # constants like 'null' (we can't use a JSON parser for).
  84. #
  85. # The alternative is to parse the entire <script> and find all image URLs by
  86. # a regular expression.
  87. img_src_script = eval_xpath_getindex(dom, '//script[contains(., "AF_initDataCallback({key: ")]', 1).text
  88. data_id_to_img_url = {}
  89. for data_id, url in _RE_JS_IMAGE_URL.findall(img_src_script):
  90. data_id_to_img_url[data_id] = url
  91. return data_id_to_img_url
  92. def get_img_url_by_data_id(data_id_to_img_url, img_node):
  93. """Get full image URL by @data-id from parent element."""
  94. data_id = eval_xpath_getindex(img_node, '../../../@data-id', 0)
  95. img_url = data_id_to_img_url.get(data_id, '')
  96. img_url = unquote(img_url.replace(r'\u00', r'%'))
  97. return img_url
  98. def request(query, params):
  99. """Google-Video search request"""
  100. lang_info = get_lang_info(params, supported_languages, language_aliases, False)
  101. query_url = (
  102. 'https://'
  103. + lang_info['subdomain']
  104. + '/search'
  105. + "?"
  106. + urlencode({'q': query, 'tbm': "isch", **lang_info['params'], 'ie': "utf8", 'oe': "utf8", 'num': 30})
  107. )
  108. if params['time_range'] in time_range_dict:
  109. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  110. if params['safesearch']:
  111. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  112. params['url'] = query_url
  113. params['cookies']['CONSENT'] = "YES+"
  114. params['headers'].update(lang_info['headers'])
  115. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  116. return params
  117. def response(resp):
  118. """Get response from google's search request"""
  119. results = []
  120. detect_google_sorry(resp)
  121. # convert the text to dom
  122. dom = html.fromstring(resp.text)
  123. img_bas64_map = scrap_out_thumbs(dom)
  124. data_id_to_img_url = parse_urls_img_from_js(dom)
  125. # parse results
  126. #
  127. # root element::
  128. # <div id="islmp" ..>
  129. # result div per image::
  130. # <div jsmodel="tTXmib"> / <div jsaction="..." data-id="..."
  131. # The data-id matches to a item in a json-data structure in::
  132. # <script nonce="I+vqelcy/01CKiBJi5Z1Ow">AF_initDataCallback({key: 'ds:1', ... data:function(){return [ ...
  133. # In this structure the link to the origin PNG, JPG or whatever is given
  134. # first link per image-div contains a <img> with the data-iid for bas64 encoded image data::
  135. # <img class="rg_i Q4LuWd" data-iid="0"
  136. # second link per image-div is the target link::
  137. # <a class="VFACy kGQAp" href="https://en.wikipedia.org/wiki/The_Sacrament_of_the_Last_Supper">
  138. # the second link also contains two div tags with the *description* and *publisher*::
  139. # <div class="WGvvNb">The Sacrament of the Last Supper ...</div>
  140. # <div class="fxgdke">en.wikipedia.org</div>
  141. root = eval_xpath(dom, '//div[@id="islmp"]')
  142. if not root:
  143. logger.error("did not find root element id='islmp'")
  144. return results
  145. root = root[0]
  146. for img_node in eval_xpath_list(root, './/img[contains(@class, "rg_i")]'):
  147. img_alt = eval_xpath_getindex(img_node, '@alt', 0)
  148. img_base64_id = eval_xpath(img_node, '@data-iid')
  149. if img_base64_id:
  150. img_base64_id = img_base64_id[0]
  151. thumbnail_src = img_bas64_map[img_base64_id]
  152. else:
  153. thumbnail_src = eval_xpath(img_node, '@src')
  154. if not thumbnail_src:
  155. thumbnail_src = eval_xpath(img_node, '@data-src')
  156. if thumbnail_src:
  157. thumbnail_src = thumbnail_src[0]
  158. else:
  159. thumbnail_src = ''
  160. link_node = eval_xpath_getindex(img_node, '../../../a[2]', 0)
  161. url = eval_xpath_getindex(link_node, '@href', 0, None)
  162. if url is None:
  163. logger.error("missing @href in node: %s", html.tostring(link_node))
  164. continue
  165. pub_nodes = eval_xpath(link_node, './div/div')
  166. pub_descr = img_alt
  167. pub_source = ''
  168. if pub_nodes:
  169. pub_descr = extract_text(pub_nodes[0])
  170. pub_source = extract_text(pub_nodes[1])
  171. src_url = get_img_url_by_data_id(data_id_to_img_url, img_node)
  172. if not src_url:
  173. src_url = thumbnail_src
  174. results.append(
  175. {
  176. 'url': url,
  177. 'title': img_alt,
  178. 'content': pub_descr,
  179. 'source': pub_source,
  180. 'img_src': src_url,
  181. 'thumbnail_src': thumbnail_src,
  182. 'template': 'images.html',
  183. }
  184. )
  185. return results