google_news.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. """
  2. Google (News)
  3. @website https://news.google.com
  4. @provide-api no
  5. @using-api no
  6. @results HTML
  7. @stable no
  8. @parse url, title, content, publishedDate
  9. """
  10. from lxml import html
  11. from searx.engines.google import _fetch_supported_languages, supported_languages_url
  12. from searx.url_utils import urlencode
  13. from searx.utils import match_language
  14. # search-url
  15. categories = ['news']
  16. paging = True
  17. language_support = True
  18. safesearch = True
  19. time_range_support = True
  20. number_of_results = 10
  21. search_url = 'https://www.google.com/search'\
  22. '?{query}'\
  23. '&tbm=nws'\
  24. '&gws_rd=cr'\
  25. '&{search_options}'
  26. time_range_attr = "qdr:{range}"
  27. time_range_dict = {'day': 'd',
  28. 'week': 'w',
  29. 'month': 'm',
  30. 'year': 'y'}
  31. # do search-request
  32. def request(query, params):
  33. search_options = {
  34. 'start': (params['pageno'] - 1) * number_of_results
  35. }
  36. if params['time_range'] in time_range_dict:
  37. search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
  38. if safesearch and params['safesearch']:
  39. search_options['safe'] = 'on'
  40. params['url'] = search_url.format(query=urlencode({'q': query}),
  41. search_options=urlencode(search_options))
  42. if params['language'] != 'all':
  43. language = match_language(params['language'], supported_languages, language_aliases).split('-')[0]
  44. if language:
  45. params['url'] += '&hl=' + language
  46. return params
  47. # get response from search-request
  48. def response(resp):
  49. results = []
  50. dom = html.fromstring(resp.text)
  51. # parse results
  52. for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'):
  53. try:
  54. r = {
  55. 'url': result.xpath('.//a[@class="l lLrAF"]')[0].attrib.get("href"),
  56. 'title': ''.join(result.xpath('.//a[@class="l lLrAF"]//text()')),
  57. 'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
  58. }
  59. except:
  60. continue
  61. imgs = result.xpath('.//img/@src')
  62. if len(imgs) and not imgs[0].startswith('data'):
  63. r['img_src'] = imgs[0]
  64. results.append(r)
  65. # return results
  66. return results