google_news.py 6.2 KB

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