我有一个脚本,它连接到我的 proxies.txt 文件中的随机代理,我已经验证它连接成功,所以它确实有效。但是,当我每次调用该函数时代码都在运行时,它将连接到它在开始时选择的同一代理。我希望它每次调用它时都更改代理。
def get_single_proxy():
proxy_list = [line.replace('\n', '') for line in open('proxies.txt', 'r')]
proxy = random.choice(proxy_list)
return proxy
PROXY = get_single_proxy()
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=3840x2160")
chrome_options.add_argument('--proxy-server=%s' % PROXY)
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chrome_driver)
async def start(ctx):
driver.get(URL)
print(PROXY)
更新:根据下面的建议,
class ProxyRotator:
def __init__(self):
#self.proxylist = [line.replace('\n', '') for line in open('proxies.txt', 'r')]
self.proxyList = ['45.72.40.18:80', '45.130.127.12:80', '45.87.243.138:80']
def get(self):
"""
Optionally you could shuffle self.proxyList every X minutes or
after all proxies had been fetched once ...
"""
proxy = self.proxyList.pop(0)
self.proxyList.append(proxy)
return proxy
pr = ProxyRotator()
for x in range(6):
print(pr.get())
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--window-size=3840x2160")
chrome_options.add_argument('--proxy-server=%s' % pr)
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chrome_driver)
async def start(ctx):
driver.get(URL)
print(pr)