google_news.py 1.9 KB

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