google_news.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. # SPDX-License-Identifier: AGPL-3.0-or-later
  2. """This is the implementation of the Google News engine.
  3. Google News has a different region handling compared to Google WEB.
  4. - the ``ceid`` argument has to be set (:py:obj:`ceid_list`)
  5. - the hl_ argument has to be set correctly (and different to Google WEB)
  6. - the gl_ argument is mandatory
  7. If one of this argument is not set correctly, the request is redirected to
  8. CONSENT dialog::
  9. https://consent.google.com/m?continue=
  10. The google news API ignores some parameters from the common :ref:`google API`:
  11. - num_ : the number of search results is ignored / there is no paging all
  12. results for a query term are in the first response.
  13. - save_ : is ignored / Google-News results are always *SafeSearch*
  14. .. _hl: https://developers.google.com/custom-search/docs/xml_results#hlsp
  15. .. _gl: https://developers.google.com/custom-search/docs/xml_results#glsp
  16. .. _num: https://developers.google.com/custom-search/docs/xml_results#numsp
  17. .. _save: https://developers.google.com/custom-search/docs/xml_results#safesp
  18. """
  19. from typing import TYPE_CHECKING
  20. from urllib.parse import urlencode
  21. import base64
  22. from lxml import html
  23. import babel
  24. from searx import locales
  25. from searx.utils import (
  26. eval_xpath,
  27. eval_xpath_list,
  28. eval_xpath_getindex,
  29. extract_text,
  30. )
  31. from searx.engines.google import fetch_traits as _fetch_traits # pylint: disable=unused-import
  32. from searx.engines.google import (
  33. get_google_info,
  34. detect_google_sorry,
  35. )
  36. from searx.enginelib.traits import EngineTraits
  37. if TYPE_CHECKING:
  38. import logging
  39. logger: logging.Logger
  40. traits: EngineTraits
  41. # about
  42. about = {
  43. "website": 'https://news.google.com',
  44. "wikidata_id": 'Q12020',
  45. "official_api_documentation": 'https://developers.google.com/custom-search',
  46. "use_official_api": False,
  47. "require_api_key": False,
  48. "results": 'HTML',
  49. }
  50. # engine dependent config
  51. categories = ['news']
  52. paging = False
  53. time_range_support = False
  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 identical for safesearch=0 and safesearch=2
  58. safesearch = True
  59. # send_accept_language_header = True
  60. def request(query, params):
  61. """Google-News search request"""
  62. sxng_locale = params.get('searxng_locale', 'en-US')
  63. ceid = locales.get_engine_locale(sxng_locale, traits.custom['ceid'], default='US:en')
  64. google_info = get_google_info(params, traits)
  65. google_info['subdomain'] = 'news.google.com' # google news has only one domain
  66. ceid_region, ceid_lang = ceid.split(':')
  67. ceid_lang, ceid_suffix = (
  68. ceid_lang.split('-')
  69. + [
  70. None,
  71. ]
  72. )[:2]
  73. google_info['params']['hl'] = ceid_lang
  74. if ceid_suffix and ceid_suffix not in ['Hans', 'Hant']:
  75. if ceid_region.lower() == ceid_lang:
  76. google_info['params']['hl'] = ceid_lang + '-' + ceid_region
  77. else:
  78. google_info['params']['hl'] = ceid_lang + '-' + ceid_suffix
  79. elif ceid_region.lower() != ceid_lang:
  80. if ceid_region in ['AT', 'BE', 'CH', 'IL', 'SA', 'IN', 'BD', 'PT']:
  81. google_info['params']['hl'] = ceid_lang
  82. else:
  83. google_info['params']['hl'] = ceid_lang + '-' + ceid_region
  84. google_info['params']['lr'] = 'lang_' + ceid_lang.split('-')[0]
  85. google_info['params']['gl'] = ceid_region
  86. query_url = (
  87. 'https://'
  88. + google_info['subdomain']
  89. + "/search?"
  90. + urlencode(
  91. {
  92. 'q': query,
  93. **google_info['params'],
  94. }
  95. )
  96. # ceid includes a ':' character which must not be urlencoded
  97. + ('&ceid=%s' % ceid)
  98. )
  99. params['url'] = query_url
  100. params['cookies'] = google_info['cookies']
  101. params['headers'].update(google_info['headers'])
  102. return params
  103. def response(resp):
  104. """Get response from google's search request"""
  105. results = []
  106. detect_google_sorry(resp)
  107. # convert the text to dom
  108. dom = html.fromstring(resp.text)
  109. for result in eval_xpath_list(dom, '//div[@class="xrnccd"]'):
  110. # The first <a> tag in the <article> contains the link to the article
  111. # The href attribute of the <a> tag is a google internal link, we have
  112. # to decode
  113. href = eval_xpath_getindex(result, './article/a/@href', 0)
  114. href = href.split('?')[0]
  115. href = href.split('/')[-1]
  116. href = base64.urlsafe_b64decode(href + '====')
  117. href = href[href.index(b'http') :].split(b'\xd2')[0]
  118. href = href.decode()
  119. title = extract_text(eval_xpath(result, './article/h3[1]'))
  120. # The pub_date is mostly a string like 'yesterday', not a real
  121. # timezone date or time. Therefore we can't use publishedDate.
  122. pub_date = extract_text(eval_xpath(result, './article//time'))
  123. pub_origin = extract_text(eval_xpath(result, './article//a[@data-n-tid]'))
  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. thumbnail = extract_text(result.xpath('preceding-sibling::a/figure/img/@src'))
  129. results.append(
  130. {
  131. 'url': href,
  132. 'title': title,
  133. 'content': content,
  134. 'thumbnail': thumbnail,
  135. }
  136. )
  137. # return results
  138. return results
  139. ceid_list = [
  140. 'AE:ar',
  141. 'AR:es-419',
  142. 'AT:de',
  143. 'AU:en',
  144. 'BD:bn',
  145. 'BE:fr',
  146. 'BE:nl',
  147. 'BG:bg',
  148. 'BR:pt-419',
  149. 'BW:en',
  150. 'CA:en',
  151. 'CA:fr',
  152. 'CH:de',
  153. 'CH:fr',
  154. 'CL:es-419',
  155. 'CN:zh-Hans',
  156. 'CO:es-419',
  157. 'CU:es-419',
  158. 'CZ:cs',
  159. 'DE:de',
  160. 'EG:ar',
  161. 'ES:es',
  162. 'ET:en',
  163. 'FR:fr',
  164. 'GB:en',
  165. 'GH:en',
  166. 'GR:el',
  167. 'HK:zh-Hant',
  168. 'HU:hu',
  169. 'ID:en',
  170. 'ID:id',
  171. 'IE:en',
  172. 'IL:en',
  173. 'IL:he',
  174. 'IN:bn',
  175. 'IN:en',
  176. 'IN:hi',
  177. 'IN:ml',
  178. 'IN:mr',
  179. 'IN:ta',
  180. 'IN:te',
  181. 'IT:it',
  182. 'JP:ja',
  183. 'KE:en',
  184. 'KR:ko',
  185. 'LB:ar',
  186. 'LT:lt',
  187. 'LV:en',
  188. 'LV:lv',
  189. 'MA:fr',
  190. 'MX:es-419',
  191. 'MY:en',
  192. 'NA:en',
  193. 'NG:en',
  194. 'NL:nl',
  195. 'NO:no',
  196. 'NZ:en',
  197. 'PE:es-419',
  198. 'PH:en',
  199. 'PK:en',
  200. 'PL:pl',
  201. 'PT:pt-150',
  202. 'RO:ro',
  203. 'RS:sr',
  204. 'RU:ru',
  205. 'SA:ar',
  206. 'SE:sv',
  207. 'SG:en',
  208. 'SI:sl',
  209. 'SK:sk',
  210. 'SN:fr',
  211. 'TH:th',
  212. 'TR:tr',
  213. 'TW:zh-Hant',
  214. 'TZ:en',
  215. 'UA:ru',
  216. 'UA:uk',
  217. 'UG:en',
  218. 'US:en',
  219. 'US:es-419',
  220. 'VE:es-419',
  221. 'VN:vi',
  222. 'ZA:en',
  223. 'ZW:en',
  224. ]
  225. """List of region/language combinations supported by Google News. Values of the
  226. ``ceid`` argument of the Google News REST API."""
  227. _skip_values = [
  228. 'ET:en', # english (ethiopia)
  229. 'ID:en', # english (indonesia)
  230. 'LV:en', # english (latvia)
  231. ]
  232. _ceid_locale_map = {'NO:no': 'nb-NO'}
  233. def fetch_traits(engine_traits: EngineTraits):
  234. _fetch_traits(engine_traits, add_domains=False)
  235. engine_traits.custom['ceid'] = {}
  236. for ceid in ceid_list:
  237. if ceid in _skip_values:
  238. continue
  239. region, lang = ceid.split(':')
  240. x = lang.split('-')
  241. if len(x) > 1:
  242. if x[1] not in ['Hant', 'Hans']:
  243. lang = x[0]
  244. sxng_locale = _ceid_locale_map.get(ceid, lang + '-' + region)
  245. try:
  246. locale = babel.Locale.parse(sxng_locale, sep='-')
  247. except babel.UnknownLocaleError:
  248. print("ERROR: %s -> %s is unknown by babel" % (ceid, sxng_locale))
  249. continue
  250. engine_traits.custom['ceid'][locales.region_tag(locale)] = ceid