25 lines
862 B
Python
25 lines
862 B
Python
import itertools
|
|
from typing import Optional, Union, List, Dict
|
|
|
|
class ProxyRotator:
|
|
def __init__(self, proxies: Optional[Union[str, List[str]]]):
|
|
# 1. 如果传入的是单个字符串,先转换成列表
|
|
if isinstance(proxies, str):
|
|
proxies = [proxies]
|
|
|
|
# 2. 如果列表存在且不为空,创建一个无限循环迭代器
|
|
if proxies:
|
|
self._proxies = itertools.cycle(proxies)
|
|
else:
|
|
self._proxies = None
|
|
|
|
def get(self) -> Optional[Dict[str, str]]:
|
|
# 3. 每次调用 get(),都从循环迭代器中取下一个代理
|
|
if self._proxies:
|
|
proxy = next(self._proxies)
|
|
# 4. 构造 requests 库需要的字典格式
|
|
return {
|
|
'http': proxy,
|
|
'https': proxy
|
|
}
|
|
return None |