google_images.py 7.5 KB

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