google_images.py 6.6 KB

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