google_news.py 5.9 KB

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