google_news.py 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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 urllib import urlencode
  12. from json import loads
  13. from searx.engines.google import _fetch_supported_languages, supported_languages_url
  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_array = params['language'].lower().split('-')
  44. params['url'] += '&lr=lang_' + language_array[0]
  45. return params
  46. # get response from search-request
  47. def response(resp):
  48. results = []
  49. dom = html.fromstring(resp.text)
  50. # parse results
  51. for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'):
  52. r = {
  53. 'url': result.xpath('.//div[@class="_cnc"]//a/@href')[0],
  54. 'title': ''.join(result.xpath('.//div[@class="_cnc"]//h3//text()')),
  55. 'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
  56. }
  57. imgs = result.xpath('.//img/@src')
  58. if len(imgs) and not imgs[0].startswith('data'):
  59. r['img_src'] = imgs[0]
  60. results.append(r)
  61. # return results
  62. return results