ProxyRefreshSchedule.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. # -*- coding: utf-8 -*-
  2. # !/usr/bin/env python
  3. """
  4. -------------------------------------------------
  5. File Name: ProxyRefreshSchedule.py
  6. Description : 代理定时刷新
  7. Author : JHao
  8. date: 2016/12/4
  9. -------------------------------------------------
  10. Change Activity:
  11. 2016/12/4: 代理定时刷新
  12. 2017/03/06: 使用LogHandler添加日志
  13. -------------------------------------------------
  14. """
  15. import sys
  16. import time
  17. import requests
  18. from multiprocessing import Process
  19. from apscheduler.schedulers.blocking import BlockingScheduler
  20. sys.path.append('../')
  21. from Manager.ProxyManager import ProxyManager
  22. from Util.LogHandler import LogHandler
  23. __author__ = 'JHao'
  24. class ProxyRefreshSchedule(ProxyManager):
  25. """
  26. 代理定时刷新
  27. """
  28. def __init__(self):
  29. ProxyManager.__init__(self)
  30. self.log = LogHandler('refresh_schedule')
  31. def valid_proxy(self):
  32. """
  33. valid_proxy
  34. :return:
  35. """
  36. self.db.changeTable(self.raw_proxy_queue)
  37. raw_proxy = self.db.pop()
  38. while raw_proxy:
  39. self.log.info('%s start valid proxy' % time.ctime())
  40. proxies = {"http": "http://{proxy}".format(proxy=raw_proxy),
  41. "https": "https://{proxy}".format(proxy=raw_proxy)}
  42. try:
  43. # 超过30秒的代理就不要了
  44. r = requests.get('https://www.baidu.com/', proxies=proxies, timeout=30, verify=False)
  45. if r.status_code == 200:
  46. self.db.changeTable(self.useful_proxy_queue)
  47. self.db.put(raw_proxy)
  48. self.log.info('proxy: %s validation passes')
  49. except Exception, e:
  50. print e
  51. pass
  52. self.db.changeTable(self.raw_proxy_queue)
  53. raw_proxy = self.db.pop()
  54. self.log.info('%s valid proxy complete' % time.ctime())
  55. def refresh_pool():
  56. pp = ProxyRefreshSchedule()
  57. pp.valid_proxy()
  58. def main(process_num=10):
  59. p = ProxyRefreshSchedule()
  60. p.refresh()
  61. pl = []
  62. for num in range(process_num):
  63. proc = Process(target=refresh_pool, args=())
  64. # proc.daemon = True
  65. pl.append(proc)
  66. for num in range(process_num):
  67. pl[num].start()
  68. for num in range(process_num):
  69. pl[num].join()
  70. if __name__ == '__main__':
  71. main()
  72. sched = BlockingScheduler()
  73. sched.add_job(main, 'interval', minutes=10)
  74. sched.start()