google_images.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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. # pylint: disable=undefined-variable
  78. params, supported_languages, language_aliases, False
  79. )
  80. logger.debug(
  81. "HTTP header Accept-Language --> %s", lang_info['headers']['Accept-Language'])
  82. query_url = 'https://' + lang_info['subdomain'] + '/search' + "?" + urlencode({
  83. 'q': query,
  84. 'tbm': "isch",
  85. **lang_info['params'],
  86. 'ie': "utf8",
  87. 'oe': "utf8",
  88. 'num': 30,
  89. })
  90. if params['time_range'] in time_range_dict:
  91. query_url += '&' + urlencode({'tbs': 'qdr:' + time_range_dict[params['time_range']]})
  92. if params['safesearch']:
  93. query_url += '&' + urlencode({'safe': filter_mapping[params['safesearch']]})
  94. params['url'] = query_url
  95. params['headers'].update(lang_info['headers'])
  96. params['headers']['Accept'] = (
  97. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  98. )
  99. return params
  100. def response(resp):
  101. """Get response from google's search request"""
  102. results = []
  103. detect_google_sorry(resp)
  104. # convert the text to dom
  105. dom = html.fromstring(resp.text)
  106. img_bas64_map = scrap_out_thumbs(dom)
  107. img_src_script = eval_xpath_getindex(
  108. dom, '//script[contains(., "AF_initDataCallback({key: ")]', 1).text
  109. # parse results
  110. #
  111. # root element::
  112. # <div id="islmp" ..>
  113. # result div per image::
  114. # <div jsmodel="tTXmib"> / <div jsaction="..." data-id="..."
  115. # The data-id matches to a item in a json-data structure in::
  116. # <script nonce="I+vqelcy/01CKiBJi5Z1Ow">AF_initDataCallback({key: 'ds:1', ... data:function(){return [ ...
  117. # In this structure the link to the origin PNG, JPG or whatever is given
  118. # first link per image-div contains a <img> with the data-iid for bas64 encoded image data::
  119. # <img class="rg_i Q4LuWd" data-iid="0"
  120. # second link per image-div is the target link::
  121. # <a class="VFACy kGQAp" href="https://en.wikipedia.org/wiki/The_Sacrament_of_the_Last_Supper">
  122. # the second link also contains two div tags with the *description* and *publisher*::
  123. # <div class="WGvvNb">The Sacrament of the Last Supper ...</div>
  124. # <div class="fxgdke">en.wikipedia.org</div>
  125. root = eval_xpath(dom, '//div[@id="islmp"]')
  126. if not root:
  127. logger.error("did not find root element id='islmp'")
  128. return results
  129. root = root[0]
  130. for img_node in eval_xpath_list(root, './/img[contains(@class, "rg_i")]'):
  131. img_alt = eval_xpath_getindex(img_node, '@alt', 0)
  132. img_base64_id = eval_xpath(img_node, '@data-iid')
  133. if img_base64_id:
  134. img_base64_id = img_base64_id[0]
  135. thumbnail_src = img_bas64_map[img_base64_id]
  136. else:
  137. thumbnail_src = eval_xpath(img_node, '@src')
  138. if not thumbnail_src:
  139. thumbnail_src = eval_xpath(img_node, '@data-src')
  140. if thumbnail_src:
  141. thumbnail_src = thumbnail_src[0]
  142. else:
  143. thumbnail_src = ''
  144. link_node = eval_xpath_getindex(img_node, '../../../a[2]', 0)
  145. url = eval_xpath_getindex(link_node, '@href', 0)
  146. pub_nodes = eval_xpath(link_node, './div/div')
  147. pub_descr = img_alt
  148. pub_source = ''
  149. if pub_nodes:
  150. pub_descr = extract_text(pub_nodes[0])
  151. pub_source = extract_text(pub_nodes[1])
  152. img_src_id = eval_xpath_getindex(img_node, '../../../@data-id', 0)
  153. src_url = scrap_img_by_id(img_src_script, img_src_id)
  154. if not src_url:
  155. src_url = thumbnail_src
  156. results.append({
  157. 'url': url,
  158. 'title': img_alt,
  159. 'content': pub_descr,
  160. 'source': pub_source,
  161. 'img_src': src_url,
  162. # 'img_format': img_format,
  163. 'thumbnail_src': thumbnail_src,
  164. 'template': 'images.html'
  165. })
  166. return results