tester.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import asyncio
  2. import aiohttp
  3. import time
  4. <<<<<<< HEAD
  5. =======
  6. >>>>>>> dbb6bb89903b1cd158470ac472a5a930f7f0978b
  7. try:
  8. from aiohttp import ClientError
  9. except:
  10. from aiohttp import ClientProxyConnectionError as ProxyConnectionError
  11. from proxypool.db import RedisClient
  12. from proxypool.setting import *
  13. class Tester(object):
  14. def __init__(self):
  15. self.redis = RedisClient()
  16. async def test_single_proxy(self, proxy):
  17. """
  18. 测试单个代理
  19. :param proxy:
  20. :return:
  21. """
  22. conn = aiohttp.TCPConnector(verify_ssl=False)
  23. async with aiohttp.ClientSession(connector=conn) as session:
  24. try:
  25. if isinstance(proxy, bytes):
  26. proxy = proxy.decode('utf-8')
  27. real_proxy = 'http://' + proxy
  28. print('正在测试', proxy)
  29. async with session.get(TEST_URL, proxy=real_proxy, timeout=15, allow_redirects=False) as response:
  30. if response.status in VALID_STATUS_CODES:
  31. self.redis.max(proxy)
  32. print('代理可用', proxy)
  33. else:
  34. self.redis.decrease(proxy)
  35. print('请求响应码不合法 ', response.status, 'IP', proxy)
  36. except (ClientError, aiohttp.client_exceptions.ClientConnectorError, asyncio.TimeoutError, AttributeError):
  37. self.redis.decrease(proxy)
  38. print('代理请求失败', proxy)
  39. def run(self):
  40. """
  41. 测试主函数
  42. :return:
  43. """
  44. print('测试器开始运行')
  45. try:
  46. proxies = self.redis.all()
  47. loop = asyncio.get_event_loop()
  48. for i in range(0, len(proxies), BATCH_TEST_SIZE):
  49. test_proxies = proxies[i:i + BATCH_TEST_SIZE]
  50. tasks = [self.test_single_proxy(proxy) for proxy in test_proxies]
  51. loop.run_until_complete(asyncio.wait(tasks))
  52. time.sleep(5)
  53. except Exception as e:
  54. print('测试器发生错误', e.args)