google_news.py 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. 'year': 'y'}
  29. # do search-request
  30. def request(query, params):
  31. search_options = {
  32. 'start': (params['pageno'] - 1) * number_of_results
  33. }
  34. if params['time_range'] in time_range_dict:
  35. search_options['tbs'] = time_range_attr.format(range=time_range_dict[params['time_range']])
  36. if safesearch and params['safesearch']:
  37. search_options['safe'] = 'on'
  38. params['url'] = search_url.format(query=urlencode({'q': query}),
  39. search_options=urlencode(search_options))
  40. if params['language'] != 'all':
  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. r = {
  51. 'url': result.xpath('.//div[@class="_cnc"]//a/@href')[0],
  52. 'title': ''.join(result.xpath('.//div[@class="_cnc"]//h3//text()')),
  53. 'content': ''.join(result.xpath('.//div[@class="st"]//text()')),
  54. }
  55. imgs = result.xpath('.//img/@src')
  56. if len(imgs) and not imgs[0].startswith('data'):
  57. r['img_src'] = imgs[0]
  58. results.append(r)
  59. # return results
  60. return results