google_news.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. # lint: pylint
  3. """This is the implementation of the google news engine. The google news API
  4. ignores some parameters from the common :ref:`google API`:
  5. - num_ : the number of search results is ignored
  6. - save_ : is ignored / Google-News results are always *SafeSearch*
  7. .. _num: https://developers.google.com/custom-search/docs/xml_results#numsp
  8. .. _save: https://developers.google.com/custom-search/docs/xml_results#safesp
  9. """
  10. # pylint: disable=invalid-name
  11. import binascii
  12. import re
  13. from urllib.parse import urlencode
  14. from base64 import b64decode
  15. from lxml import html
  16. from searx.utils import (
  17. eval_xpath,
  18. eval_xpath_list,
  19. eval_xpath_getindex,
  20. extract_text,
  21. )
  22. # pylint: disable=unused-import
  23. from searx.engines.google import (
  24. fetch_traits,
  25. supported_languages_url,
  26. _fetch_supported_languages,
  27. )
  28. # pylint: enable=unused-import
  29. from searx.engines.google import (
  30. get_lang_info,
  31. detect_google_sorry,
  32. )
  33. # about
  34. about = {
  35. "website": 'https://news.google.com',
  36. "wikidata_id": 'Q12020',
  37. "official_api_documentation": 'https://developers.google.com/custom-search',
  38. "use_official_api": False,
  39. "require_api_key": False,
  40. "results": 'HTML',
  41. }
  42. # compared to other google engines google-news has a different time range
  43. # support. The time range is included in the search term.
  44. time_range_dict = {
  45. 'day': 'when:1d',
  46. 'week': 'when:7d',
  47. 'month': 'when:1m',
  48. 'year': 'when:1y',
  49. }
  50. # engine dependent config
  51. categories = ['news']
  52. paging = False
  53. use_locale_domain = True
  54. time_range_support = True
  55. # Google-News results are always *SafeSearch*. Option 'safesearch' is set to
  56. # False here, otherwise checker will report safesearch-errors::
  57. #
  58. # safesearch : results are identitical for safesearch=0 and safesearch=2
  59. safesearch = False
  60. send_accept_language_header = True
  61. def request(query, params):
  62. """Google-News search request"""
  63. lang_info = get_lang_info(params, supported_languages, language_aliases, False)
  64. # google news has only one domain
  65. lang_info['subdomain'] = 'news.google.com'
  66. ceid = "%s:%s" % (lang_info['country'], lang_info['language'])
  67. # google news redirects en to en-US
  68. if lang_info['params']['hl'] == 'en':
  69. lang_info['params']['hl'] = 'en-US'
  70. # Very special to google-news compared to other google engines, the time
  71. # range is included in the search term.
  72. if params['time_range']:
  73. query += ' ' + time_range_dict[params['time_range']]
  74. query_url = (
  75. 'https://'
  76. + lang_info['subdomain']
  77. + '/search'
  78. + "?"
  79. + urlencode({'q': query, **lang_info['params'], 'ie': "utf8", 'oe': "utf8", 'gl': lang_info['country']})
  80. + ('&ceid=%s' % ceid)
  81. ) # ceid includes a ':' character which must not be urlencoded
  82. params['url'] = query_url
  83. params['cookies']['CONSENT'] = "YES+"
  84. params['headers'].update(lang_info['headers'])
  85. params['headers']['Accept'] = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8'
  86. return params
  87. def response(resp):
  88. """Get response from google's search request"""
  89. results = []
  90. detect_google_sorry(resp)
  91. # convert the text to dom
  92. dom = html.fromstring(resp.text)
  93. for result in eval_xpath_list(dom, '//div[@class="xrnccd"]'):
  94. # The first <a> tag in the <article> contains the link to the
  95. # article The href attribute of the <a> is a google internal link,
  96. # we can't use. The real link is hidden in the jslog attribute:
  97. #
  98. # <a ...
  99. # jslog="95014; 4:https://www.cnn.com/.../index.html; track:click"
  100. # href="./articles/CAIiENu3nGS...?hl=en-US&amp;gl=US&amp;ceid=US%3Aen"
  101. # ... />
  102. jslog = eval_xpath_getindex(result, './article/a/@jslog', 0)
  103. url = re.findall('http[^;]*', jslog)
  104. if url:
  105. url = url[0]
  106. else:
  107. # The real URL is base64 encoded in the json attribute:
  108. # jslog="95014; 5:W251bGwsbnVsbCxudW...giXQ==; track:click"
  109. jslog = jslog.split(";")[1].split(':')[1].strip()
  110. try:
  111. padding = (4 - (len(jslog) % 4)) * "="
  112. jslog = b64decode(jslog + padding)
  113. except binascii.Error:
  114. # URL can't be read, skip this result
  115. continue
  116. # now we have : b'[null, ... null,"https://www.cnn.com/.../index.html"]'
  117. url = re.findall('http[^;"]*', str(jslog))[0]
  118. # the first <h3> tag in the <article> contains the title of the link
  119. title = extract_text(eval_xpath(result, './article/h3[1]'))
  120. # The pub_date is mostly a string like 'yesertday', not a real
  121. # timezone date or time. Therefore we can't use publishedDate.
  122. pub_date = extract_text(eval_xpath(result, './article/div[1]/div[1]/time'))
  123. pub_origin = extract_text(eval_xpath(result, './article/div[1]/div[1]/a'))
  124. content = ' / '.join([x for x in [pub_origin, pub_date] if x])
  125. # The image URL is located in a preceding sibling <img> tag, e.g.:
  126. # "https://lh3.googleusercontent.com/DjhQh7DMszk.....z=-p-h100-w100"
  127. # These URL are long but not personalized (double checked via tor).
  128. img_src = extract_text(result.xpath('preceding-sibling::a/figure/img/@src'))
  129. results.append(
  130. {
  131. 'url': url,
  132. 'title': title,
  133. 'content': content,
  134. 'img_src': img_src,
  135. }
  136. )
  137. # return results
  138. return results