tester.py 2.0 KB

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