google_images.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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 import logger
  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 (
  27. supported_languages_url
  28. , _fetch_supported_languages
  29. )
  30. # pylint: enable=unused-import
  31. logger = logger.getChild('google images')
  32. # about
  33. about = {
  34. "website": 'https://images.google.com',
  35. "wikidata_id": 'Q521550',
  36. "official_api_documentation": 'https://developers.google.com/custom-search',
  37. "use_official_api": False,
  38. "require_api_key": False,
  39. "results": 'HTML',
  40. }
  41. # engine dependent config
  42. categories = ['images']
  43. paging = False
  44. use_locale_domain = True
  45. time_range_support = True
  46. safesearch = True
  47. filter_mapping = {
  48. 0: 'images',
  49. 1: 'active',
  50. 2: 'active'
  51. }
  52. def scrap_out_thumbs(dom):
  53. """Scrap out thumbnail data from <script> tags.
  54. """
  55. ret_val = {}
  56. for script in eval_xpath(dom, '//script[contains(., "_setImgSrc(")]'):
  57. _script = script.text
  58. # _setImgSrc('0','data:image\/jpeg;base64,\/9j\/4AAQSkZJR ....');
  59. _thumb_no, _img_data = _script[len("_setImgSrc("):-2].split(",", 1)
  60. _thumb_no = _thumb_no.replace("'", "")
  61. _img_data = _img_data.replace("'", "")
  62. _img_data = _img_data.replace(r"\/", r"/")
  63. ret_val[_thumb_no] = _img_data.replace(r"\x3d", "=")
  64. return ret_val
  65. def scrap_img_by_id(script, data_id):
  66. """Get full image URL by data-id in parent element
  67. """
  68. img_url = ''
  69. _script = script.split('\n')
  70. for i, line in enumerate(_script):
  71. if 'gstatic.com/images' in line and data_id in line and i + 1 < len(_script):
  72. url_line = _script[i + 1]
  73. img_url = url_line.split('"')[1]
  74. img_url = unquote(img_url.replace(r'\u00', r'%'))
  75. return img_url
  76. def request(query, params):
  77. """Google-Video search request"""
  78. lang_info = get_lang_info(
  79. # pylint: disable=undefined-variable
  80. params, supported_languages, language_aliases, False
  81. )
  82. logger.debug(
  83. "HTTP header Accept-Language --> %s", lang_info['headers']['Accept-Language'])
  84. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  85. 'q': query,
  86. 'tbm': "isch",
  87. **lang_info['params'],
  88. 'ie': "utf8",
  89. 'oe': "utf8",
  90. 'num': 30,
  91. })
  92. if params['time_range'] in time_range_dict:
  93. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  94. if params['safesearch']:
  95. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  96. params['url'] = query_url
  97. params['headers'].update(lang_info['headers'])
  98. params['headers']['Accept'] = (
  99. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  100. )
  101. return params
  102. def response(resp):
  103. """Get response from google's search request"""
  104. results = []
  105. detect_google_sorry(resp)
  106. # convert the text to dom
  107. dom = html.fromstring(resp.text)
  108. img_bas64_map = scrap_out_thumbs(dom)
  109. img_src_script = eval_xpath_getindex(
  110. dom, '//script[contains(., "AF_initDataCallback({key: ")]', 1).text
  111. # parse results
  112. #
  113. # root element::
  114. # <div id="islmp" ..>
  115. # result div per image::
  116. # <div jsmodel="tTXmib"> / <div jsaction="..." data-id="..."
  117. # The data-id matches to a item in a json-data structure in::
  118. # <script nonce="I+vqelcy/01CKiBJi5Z1Ow">AF_initDataCallback({key: 'ds:1', ... data:function(){return [ ...
  119. # In this structure the link to the origin PNG, JPG or whatever is given
  120. # first link per image-div contains a <img> with the data-iid for bas64 encoded image data::
  121. # <img class="rg_i Q4LuWd" data-iid="0"
  122. # second link per image-div is the target link::
  123. # <a class="VFACy kGQAp" href="https://en.wikipedia.org/wiki/The_Sacrament_of_the_Last_Supper">
  124. # the second link also contains two div tags with the *description* and *publisher*::
  125. # <div class="WGvvNb">The Sacrament of the Last Supper ...</div>
  126. # <div class="fxgdke">en.wikipedia.org</div>
  127. root = eval_xpath(dom, '//div[@id="islmp"]')
  128. if not root:
  129. logger.error("did not find root element id='islmp'")
  130. return results
  131. root = root[0]
  132. for img_node in eval_xpath_list(root, './/img[contains(@class, "rg_i")]'):
  133. img_alt = eval_xpath_getindex(img_node, '@alt', 0)
  134. img_base64_id = eval_xpath(img_node, '@data-iid')
  135. if img_base64_id:
  136. img_base64_id = img_base64_id[0]
  137. thumbnail_src = img_bas64_map[img_base64_id]
  138. else:
  139. thumbnail_src = eval_xpath(img_node, '@src')
  140. if not thumbnail_src:
  141. thumbnail_src = eval_xpath(img_node, '@data-src')
  142. if thumbnail_src:
  143. thumbnail_src = thumbnail_src[0]
  144. else:
  145. thumbnail_src = ''
  146. link_node = eval_xpath_getindex(img_node, '../../../a[2]', 0)
  147. url = eval_xpath_getindex(link_node, '@href', 0)
  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