Selenium Webdriver Firefox 52 Python每次运行都选择随机代理

2024-06-02 07:59:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试在每个FireFox代理上随机运行一个新的代理。我尝试了很多方法,但只有这一种方法有效,但不知道如何使其随机:

profile.set_preference("network.proxy.type", 1)
            profile.set_preference("network.proxy.http", "Host")
            profile.set_preference("network.proxy.http_port", port)
            browser = webdriver.Firefox(profile)

我试过这个例子,但没有奏效:

^{pr2}$

这是我最好的方法,因为我可以使用:

myProxy = random.choice(open('data.txt').readlines())

我试图从文本文件中获取代理,但不知道如何随机:

with open('IPs.txt') as proxylist:
for line in proxylist: 
    proxyserv, proxyport = line.split(':') 
    proxy= proxyserv , proxyport 

最后我试过:

def random_line():
line_num = 0
selected_line = ''
with open('IPs.txt') as f:
    while 1:
        line = f.readline()
        if not line: break
        line_num += 1
        if random.uniform(0, line_num) < 1:
            selected_line = line
return selected_line.strip() 

这一个得到了一个随机行,但不知道如何解析结果 X=IP Y=端口 然后:

profile.set_preference("network.proxy.type", 1)
        profile.set_preference("network.proxy.http", "RANDOM IP")
        profile.set_preference("network.proxy.http_port", Random PORT)
        browser = webdriver.Firefox(profile)

Tags: 方法txthttp代理portlinerandomnetwork
1条回答
网友
1楼 · 发布于 2024-06-02 07:59:31

Port必须是整数,可以使用:

import random
myProxy = random.choice(open('IPs.txt').readlines())
parts = myProxy.strip().split(":") # strip removes spaces and line breaks
host = parts[0]
port = int(parts[1]) # port needs to be an integer

相关问题 更多 >