google_news.py 7.7 KB

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