google_news.py 6.2 KB

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