MediaCrawler/proxy/proxy_ip_pool.py

111 lines
3.4 KiB
Python
Raw Normal View History

2023-12-02 08:14:36 +00:00
# -*- coding: utf-8 -*-
# @Author : relakkes@gmail.com
# @Time : 2023/12/2 13:45
# @Desc : ip代理池实现
import random
2024-04-05 02:44:05 +00:00
from typing import Dict, List
2023-12-02 08:14:36 +00:00
import httpx
from tenacity import retry, stop_after_attempt, wait_fixed
2024-04-05 02:44:05 +00:00
import config
from proxy.providers import new_jisu_http_proxy, new_kuai_daili_proxy
2023-12-02 08:14:36 +00:00
from tools import utils
2024-04-05 02:44:05 +00:00
from .base_proxy import ProxyProvider
from .types import IpInfoModel, ProviderNameEnum
2023-12-02 08:14:36 +00:00
class ProxyIpPool:
2024-04-05 02:44:05 +00:00
def __init__(self, ip_pool_count: int, enable_validate_ip: bool, ip_provider: ProxyProvider) -> None:
"""
Args:
ip_pool_count:
enable_validate_ip:
ip_provider:
"""
2023-12-02 08:14:36 +00:00
self.valid_ip_url = "https://httpbin.org/ip" # 验证 IP 是否有效的地址
self.ip_pool_count = ip_pool_count
self.enable_validate_ip = enable_validate_ip
self.proxy_list: List[IpInfoModel] = []
2024-04-05 02:44:05 +00:00
self.ip_provider: ProxyProvider = ip_provider
2023-12-02 08:14:36 +00:00
async def load_proxies(self) -> None:
"""
2024-04-05 02:44:05 +00:00
加载IP代理
Returns:
2023-12-02 08:14:36 +00:00
"""
2024-04-05 02:44:05 +00:00
self.proxy_list = await self.ip_provider.get_proxies(self.ip_pool_count)
2023-12-02 08:14:36 +00:00
2024-04-05 02:44:05 +00:00
async def _is_valid_proxy(self, proxy: IpInfoModel) -> bool:
2023-12-02 08:14:36 +00:00
"""
验证代理IP是否有效
:param proxy:
:return:
"""
2024-04-05 02:44:05 +00:00
utils.logger.info(f"[ProxyIpPool._is_valid_proxy] testing {proxy.ip} is it valid ")
2023-12-02 08:14:36 +00:00
try:
2024-01-13 07:50:02 +00:00
httpx_proxy = {
f"{proxy.protocol}": f"http://{proxy.user}:{proxy.password}@{proxy.ip}:{proxy.port}"
2023-12-07 16:10:04 +00:00
}
2024-01-13 07:50:02 +00:00
async with httpx.AsyncClient(proxies=httpx_proxy) as client:
2023-12-02 08:14:36 +00:00
response = await client.get(self.valid_ip_url)
if response.status_code == 200:
return True
else:
return False
except Exception as e:
2024-04-05 02:44:05 +00:00
utils.logger.info(f"[ProxyIpPool._is_valid_proxy] testing {proxy.ip} err: {e}")
2023-12-02 08:14:36 +00:00
raise e
@retry(stop=stop_after_attempt(3), wait=wait_fixed(1))
async def get_proxy(self) -> IpInfoModel:
"""
从代理池中随机提取一个代理IP
:return:
"""
if len(self.proxy_list) == 0:
2024-04-05 02:44:05 +00:00
await self._reload_proxies()
2023-12-02 08:14:36 +00:00
proxy = random.choice(self.proxy_list)
2024-04-13 10:04:33 +00:00
self.proxy_list.remove(proxy) # 取出来一个IP就应该移出掉
2023-12-02 08:14:36 +00:00
if self.enable_validate_ip:
2024-04-05 02:44:05 +00:00
if not await self._is_valid_proxy(proxy):
2023-12-02 08:14:36 +00:00
raise Exception("[ProxyIpPool.get_proxy] current ip invalid and again get it")
return proxy
2024-04-05 02:44:05 +00:00
async def _reload_proxies(self):
2023-12-02 08:14:36 +00:00
"""
# 重新加载代理池
:return:
"""
self.proxy_list = []
await self.load_proxies()
2024-04-05 02:44:05 +00:00
IpProxyProvider: Dict[str, ProxyProvider] = {
ProviderNameEnum.JISHU_HTTP_PROVIDER.value: new_jisu_http_proxy(),
ProviderNameEnum.KUAI_DAILI_PROVIDER.value: new_kuai_daili_proxy()
}
async def create_ip_pool(ip_pool_count: int, enable_validate_ip: bool) -> ProxyIpPool:
2023-12-02 08:14:36 +00:00
"""
创建 IP 代理池
2024-04-05 02:44:05 +00:00
:param ip_pool_count: ip池子的数量
:param enable_validate_ip: 是否开启验证IP代理
2023-12-02 08:14:36 +00:00
:return:
"""
2024-04-05 02:44:05 +00:00
pool = ProxyIpPool(ip_pool_count=ip_pool_count,
enable_validate_ip=enable_validate_ip,
ip_provider=IpProxyProvider.get(config.IP_PROXY_PROVIDER_NAME)
)
2023-12-02 08:14:36 +00:00
await pool.load_proxies()
return pool
if __name__ == '__main__':
pass