ProxyRefreshSchedule.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. -------------------------------------------------
  13. """
  14. __author__ = 'JHao'
  15. import sys
  16. import time
  17. from multiprocessing import Process
  18. import requests
  19. from apscheduler.schedulers.blocking import BlockingScheduler
  20. sys.path.append('../')
  21. from Manager.ProxyManager import ProxyManager
  22. class ProxyRefreshSchedule(ProxyManager):
  23. """
  24. 代理定时刷新
  25. """
  26. def __init__(self):
  27. ProxyManager.__init__(self)
  28. def validProxy(self):
  29. self.db.changeTable(self.raw_proxy_queue)
  30. raw_proxy = self.db.pop()
  31. while raw_proxy:
  32. proxies = {"http": "http://{proxy}".format(proxy=raw_proxy),
  33. "https": "https://{proxy}".format(proxy=raw_proxy)}
  34. try:
  35. r = requests.get('https://www.baidu.com/', proxies=proxies, timeout=50, verify=False)
  36. if r.status_code == 200:
  37. self.db.changeTable(self.useful_proxy_queue)
  38. self.db.put(raw_proxy)
  39. except Exception as e:
  40. # print e
  41. pass
  42. self.db.changeTable(self.raw_proxy_queue)
  43. raw_proxy = self.db.pop()
  44. print 'validate a proxy'
  45. def refreshPool():
  46. pp = ProxyRefreshSchedule()
  47. pp.validProxy()
  48. def main(process_num=100):
  49. p = ProxyRefreshSchedule()
  50. p.refresh()
  51. pl = []
  52. for num in range(process_num):
  53. P = Process(target=refreshPool, args=())
  54. P.daemon = True
  55. pl.append(P)
  56. for num in range(process_num):
  57. pl[num].start()
  58. print 'all proc start'
  59. for num in range(process_num):
  60. pl[num].join()
  61. #
  62. # print '{time}: refresh complete!'.format(time=time.ctime())
  63. def main(process_num=100):
  64. p = ProxyRefreshSchedule()
  65. p.refresh()
  66. for num in range(process_num):
  67. P = Process(target=refreshPool, args=())
  68. P.daemon = True
  69. P.start()
  70. P.join()
  71. print '{time}: refresh complete!'.format(time=time.ctime())
  72. if __name__ == '__main__':
  73. # pp = ProxyRefreshSchedule()
  74. # pp.main()
  75. # main()
  76. sched = BlockingScheduler()
  77. sched.add_job(main, 'interval', seconds=2)
  78. sched.start()