google_news.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if params['language'] != 'all':
  42. language_array = params['language'].lower().split('-')
  43. params['url'] += '&lr=lang_' + language_array[0]
  44. return params
  45. # get response from search-request
  46. def response(resp):
  47. results = []
  48. dom = html.fromstring(resp.text)
  49. # parse results
  50. for result in dom.xpath('//div[@class="g"]|//div[@class="g _cy"]'):
  51. try:
  52. r = {
  53. 'url': result.xpath('.//a[@class="l _PMs"]')[0].attrib.get("href"),
  54. 'title': ''.join(result.xpath('.//a[@class="l _PMs"]//text()')),
  55. 'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
  56. }
  57. except:
  58. continue
  59. imgs = result.xpath('.//img/@src')
  60. if len(imgs) and not imgs[0].startswith('data'):
  61. r['img_src'] = imgs[0]
  62. results.append(r)
  63. # return results
  64. return results