google_images.py 7.8 KB

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