google_images.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. import urllib
  20. from lxml import html
  21. from flask_babel import gettext
  22. from searx import logger
  23. from searx.url_utils import urlencode, urlparse
  24. from searx.utils import eval_xpath
  25. from searx.engines.xpath import extract_text
  26. # pylint: disable=unused-import
  27. from searx.engines.google import (
  28. supported_languages_url,
  29. _fetch_supported_languages,
  30. )
  31. # pylint: enable=unused-import
  32. from searx.engines.google import (
  33. get_lang_country,
  34. google_domains,
  35. time_range_dict,
  36. )
  37. logger = logger.getChild('google images')
  38. # engine dependent config
  39. categories = ['images']
  40. paging = False
  41. language_support = True
  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 = dict()
  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:
  70. url_line = _script[i + 1]
  71. img_url = url_line.split('"')[1]
  72. img_url = urllib.parse.unquote(img_url.replace(r'\u00', r'%'))
  73. return img_url
  74. def request(query, params):
  75. """Google-Video search request"""
  76. language, country, lang_country = get_lang_country(
  77. # pylint: disable=undefined-variable
  78. params, supported_languages, language_aliases
  79. )
  80. subdomain = 'www.' + google_domains.get(country.upper(), 'google.com')
  81. query_url = 'https://' + subdomain + '/search' + "?" + urlencode({
  82. 'q': query,
  83. 'tbm': "isch",
  84. 'hl': lang_country,
  85. 'lr': "lang_" + language,
  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. logger.debug("query_url --> %s", query_url)
  96. params['headers']['Accept-Language'] = (
  97. "%s,%s;q=0.8,%s;q=0.5" % (lang_country, language, language))
  98. logger.debug(
  99. "HTTP Accept-Language --> %s", params['headers']['Accept-Language'])
  100. params['headers']['Accept'] = (
  101. 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  102. )
  103. # params['google_subdomain'] = subdomain
  104. return params
  105. def response(resp):
  106. """Get response from google's search request"""
  107. results = []
  108. # detect google sorry
  109. resp_url = urlparse(resp.url)
  110. if resp_url.netloc == 'sorry.google.com' or resp_url.path == '/sorry/IndexRedirect':
  111. raise RuntimeWarning('sorry.google.com')
  112. if resp_url.path.startswith('/sorry'):
  113. raise RuntimeWarning(gettext('CAPTCHA required'))
  114. # which subdomain ?
  115. # subdomain = resp.search_params.get('google_subdomain')
  116. # convert the text to dom
  117. dom = html.fromstring(resp.text)
  118. img_bas64_map = scrap_out_thumbs(dom)
  119. img_src_script = eval_xpath(dom, '//script[contains(., "AF_initDataCallback({key: ")]')[1].text
  120. # parse results
  121. #
  122. # root element::
  123. # <div id="islmp" ..>
  124. # result div per image::
  125. # <div jsmodel="tTXmib"> / <div jsaction="..." data-id="..."
  126. # The data-id matches to a item in a json-data structure in::
  127. # <script nonce="I+vqelcy/01CKiBJi5Z1Ow">AF_initDataCallback({key: 'ds:1', ... data:function(){return [ ...
  128. # In this structure the link to the origin PNG, JPG or whatever is given
  129. # first link per image-div contains a <img> with the data-iid for bas64 encoded image data::
  130. # <img class="rg_i Q4LuWd" data-iid="0"
  131. # second link per image-div is the target link::
  132. # <a class="VFACy kGQAp" href="https://en.wikipedia.org/wiki/The_Sacrament_of_the_Last_Supper">
  133. # the second link also contains two div tags with the *description* and *publisher*::
  134. # <div class="WGvvNb">The Sacrament of the Last Supper ...</div>
  135. # <div class="fxgdke">en.wikipedia.org</div>
  136. root = eval_xpath(dom, '//div[@id="islmp"]')
  137. if not root:
  138. logger.error("did not find root element id='islmp'")
  139. return results
  140. root = root[0]
  141. for img_node in eval_xpath(root, './/img[contains(@class, "rg_i")]'):
  142. try:
  143. img_alt = eval_xpath(img_node, '@alt')[0]
  144. img_base64_id = eval_xpath(img_node, '@data-iid')
  145. if img_base64_id:
  146. img_base64_id = img_base64_id[0]
  147. thumbnail_src = img_bas64_map[img_base64_id]
  148. else:
  149. thumbnail_src = eval_xpath(img_node, '@src')
  150. if not thumbnail_src:
  151. thumbnail_src = eval_xpath(img_node, '@data-src')
  152. if thumbnail_src:
  153. thumbnail_src = thumbnail_src[0]
  154. else:
  155. thumbnail_src = ''
  156. link_node = eval_xpath(img_node, '../../../a[2]')[0]
  157. url = eval_xpath(link_node, '@href')[0]
  158. pub_nodes = eval_xpath(link_node, './div/div')
  159. pub_descr = img_alt
  160. pub_source = ''
  161. if pub_nodes:
  162. pub_descr = extract_text(pub_nodes[0])
  163. pub_source = extract_text(pub_nodes[1])
  164. img_src_id = eval_xpath(img_node, '../../../@data-id')[0]
  165. src_url = scrap_img_by_id(img_src_script, img_src_id)
  166. if not src_url:
  167. src_url = thumbnail_src
  168. results.append({
  169. 'url': url,
  170. 'title': img_alt,
  171. 'content': pub_descr,
  172. 'source': pub_source,
  173. 'img_src': src_url,
  174. # 'img_format': img_format,
  175. 'thumbnail_src': thumbnail_src,
  176. 'template': 'images.html'
  177. })
  178. except Exception as e: # pylint: disable=broad-except
  179. logger.error(e, exc_info=True)
  180. # from lxml import etree
  181. # logger.debug(etree.tostring(img_node, pretty_print=True))
  182. # import pdb
  183. # pdb.set_trace()
  184. continue
  185. return results