google_news.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. # search-url
  14. categories = ['news']
  15. paging = True
  16. language_support = True
  17. safesearch = True
  18. time_range_support = True
  19. number_of_results = 10
  20. search_url = 'https://www.google.com/search'\
  21. '?{query}'\
  22. '&tbm=nws'\
  23. '&gws_rd=cr'\
  24. '&{search_options}'
  25. time_range_attr = "qdr:{range}"
  26. time_range_dict = {'day': 'd',
  27. 'week': 'w',
  28. 'month': 'm',
  29. 'year': 'y'}
  30. # do search-request
  31. def request(query, params):
  32. search_options = {
  33. 'start': (params['pageno'] - 1) * number_of_results
  34. }
  35. if params['time_range'] in time_range_dict:
  36. search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
  37. if safesearch and params['safesearch']:
  38. search_options['safe'] = 'on'
  39. params['url'] = search_url.format(query=urlencode({'q': query}),
  40. search_options=urlencode(search_options))
  41. language_array = params['language'].lower().split('-')
  42. params['url'] += '&lr=lang_' + language_array[0]
  43. return params
  44. # get response from search-request
  45. def response(resp):
  46. results = []
  47. dom = html.fromstring(resp.text)
  48. # parse results
  49. for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'):
  50. try:
  51. r = {
  52. 'url': result.xpath('.//a[@class="l _PMs"]')[0].attrib.get("href"),
  53. 'title': ''.join(result.xpath('.//a[@class="l _PMs"]//text()')),
  54. 'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
  55. }
  56. except:
  57. continue
  58. imgs = result.xpath('.//img/@src')
  59. if len(imgs) and not imgs[0].startswith('data'):
  60. r['img_src'] = imgs[0]
  61. results.append(r)
  62. # return results
  63. return results