Need Proxy?

BotProxy: Rotating Proxies Made for professionals. Really fast connection. Built-in IP rotation. Fresh IPs every day.

Find out more


Selenium Webdriver Firefox 52 Python select random proxy every run

Question

I tried to setup a new random proxy for each run on FireFox. Itried many ways,but only this one works but can't figure how to make it random:

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)

I tried this example but not worked:

from selenium.webdriver.common.proxy import *
myProxy = "xx.xx.xx.xx:xxxx"

proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
'httpProxy': myProxy,
'ftpProxy': myProxy,
'sslProxy': myProxy,
'noProxy': '' # set this value as desired
})  
driver = webdriver.Firefox(proxy=proxy)
driver.get("http://www.google.com")

This is the best way for me because i can use:

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

I tried to get proxies from text file this work but don't know how to randomize:

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

And lastlly i tried:

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()

This one get random line but can't figure out how to parse the result to X= IP Y= PORT and then:

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)

Answer

Port needs to be an integer, you may want to use:

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

cc by-sa 3.0