import random import requests class ProxyManager: def __init__(self): self.proxies = [] def import_proxies(self, file_path): """ 导入代理列表,支持文件路径,格式为 host:port:user:password """ try: with open(file_path, 'r') as file: content = file.read().replace('\r\n', '\n') # 替换 Windows 风格换行符 lines = content.strip().split('\n') for line in lines: parts = line.split(':') if len(parts) == 4: # 确保格式正确 proxy = { 'host': parts[0], 'port': parts[1], 'user': parts[2], 'password': parts[3], 'protocol': 'http' } self.proxies.append(proxy) except FileNotFoundError: print(f"Error: File not found at {file_path}.") return False except Exception as e: print(f"Error: {str(e)}") return False return True def get_random_proxy(self): """ 随机获取一个代理 """ if not self.proxies: print("No proxies available.") return None return random.choice(self.proxies) def test_proxy(self, proxy): """ 测试代理的对外 IP :param proxy: 格式为 {'host': '...', 'port': '...', 'user': '...', 'password': '...', 'protocol': '...'} """ if not proxy: print("Invalid proxy provided.") return None proxy_url = f"{proxy['protocol']}://{proxy['user']}:{proxy['password']}@{proxy['host']}:{proxy['port']}" proxies = {'http': proxy_url, 'https': proxy_url} try: response = requests.get("http://jsonip.com", proxies=proxies, timeout=5) if response.status_code == 200: return response.json() else: print(f"Failed with status code: {response.status_code}") return None except requests.RequestException as e: print(f"Request failed: {str(e)}") return None def is_empty(self): return not self.proxies def get_and_test_random_proxy(self): """ 从代理列表中随机获取一个代理,测试联通性,并从列表中移除 """ if not self.proxies: print("No proxies available.") return None proxy = random.choice(self.proxies) test_result = self.test_proxy(proxy) if test_result: print(f"Proxy works: {test_result}") self.proxies.remove(proxy) # 移除成功的代理 return proxy, test_result else: print("Proxy failed. Removing from the list.") self.proxies.remove(proxy) # 移除失败的代理 return None, None if __name__ == "__main__": manager = ProxyManager() print(f'测试是否是空的:{manager.is_empty()}') print(manager.import_proxies('IP.txt')) print(f'再测试是否是空的:{manager.is_empty()}') random_proxy = manager.get_random_proxy() print(f"获取到的随机代理:{random_proxy}") test_result = manager.test_proxy(random_proxy) print(f"随机代理的出口 IP:{test_result}") proxy, result = manager.get_and_test_random_proxy() if result: print(f"测试成功 : {result},取得的代理是:{proxy},这个代理已经从代理管理器里移除。") else: print("测试失败.")