google_news.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  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. def request(query, params):
  60. """Google-News search request"""
  61. lang_info = get_lang_info(params, supported_languages, language_aliases, False)
  62. logger.debug("HTTP header Accept-Language --> %s", lang_info['headers']['Accept-Language'])
  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(
  79. {'q': query, **lang_info['params'], 'ie': "utf8", 'oe': "utf8", 'gl': lang_info['country'], 'ucbcb': 1}
  80. )
  81. + ('&ceid=%s' % ceid)
  82. ) # ceid includes a ':' character which must not be urlencoded
  83. params['url'] = query_url
  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 cant 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 first <div> tag in the <article> contains the content of the link
  121. content = extract_text(eval_xpath(result, './article/div[1]'))
  122. # the second <div> tag contains origin publisher and the publishing date
  123. pub_date = extract_text(eval_xpath(result, './article/div[2]//time'))
  124. pub_origin = extract_text(eval_xpath(result, './article/div[2]//a'))
  125. pub_info = []
  126. if pub_origin:
  127. pub_info.append(pub_origin)
  128. if pub_date:
  129. # The pub_date is mostly a string like 'yesertday', not a real
  130. # timezone date or time. Therefore we can't use publishedDate.
  131. pub_info.append(pub_date)
  132. pub_info = ', '.join(pub_info)
  133. if pub_info:
  134. content = pub_info + ': ' + content
  135. # The image URL is located in a preceding sibling <img> tag, e.g.:
  136. # "https://lh3.googleusercontent.com/DjhQh7DMszk.....z=-p-h100-w100"
  137. # These URL are long but not personalized (double checked via tor).
  138. img_src = extract_text(result.xpath('preceding-sibling::a/figure/img/@src'))
  139. results.append(
  140. {
  141. 'url': url,
  142. 'title': title,
  143. 'content': content,
  144. 'img_src': img_src,
  145. }
  146. )
  147. # return results
  148. return results