google_images.py 7.4 KB

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