google_news.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 urllib.parse import urlencode
  11. from lxml import html
  12. from searx.utils import match_language
  13. from searx.engines.google import _fetch_supported_languages, supported_languages_url # NOQA # pylint: disable=unused-import
  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