google_images.py 6.4 KB

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