python – How to make friends selenium and proxy?

Question:

I wrote parsing a proxy from a file and sending the data I need on the page. How do I launch the webdriver through a proxy now?

# -*- coding: utf8 -*-
import os
import sys
from selenium import webdriver
from multiprocessing.dummy import Pool as ThreadPool

path = os.path.realpath(os.path.dirname(sys.argv[0]))
phantomjs_path = r'/var/www/goodwin/hulk/phantomjs/bin/phantomjs'

def proxyread():
    try:
        with open(path+'/proxy-rus.txt', 'rb') as proxyfile:
            proxylist = proxyfile.read().split('\n')
    except Exception:
        with open(path+'/proxy-rus.txt', 'wb') as proxyfile:
            n.write()
        proxylist = False
    return proxylist

def poster():
    comm = unicode(' ', 'utf8')
    browser = webdriver.PhantomJS(executable_path=phantomjs_path, service_log_path=os.path.devnull)
    browser.set_window_size(1024, 768)
    browser.get("https://example.com")
    browser.implicitly_wait(5)
    browser.find_element_by_id(r"reply").click()
    browser.implicitly_wait(0.1)
    browser.find_element_by_name(r"comment").send_keys(comm)
    browser.find_element_by_css_selector(r'input[id=subject]').send_keys(comm)
    browser.find_element_by_css_selector(r'input[id=name]').send_keys(comm)
    browser.find_element_by_css_selector(r'input[type=file]').send_keys(r'1.jpg')
    browser.find_element_by_name(r"submit").click()

poster()

Answer:

The short answer is that selenium most likely uses a system proxy. It is set differently in different operating systems, your K.O.

More details in selenium help: http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp

For PhantomJS, use the following code option:

service_args = [

    '--proxy=127.0.0.1:9999',
    '--proxy-type=socks5',
    ]
browser = webdriver.PhantomJS('../path_to/phantomjs',service_args=service_args)
Scroll to Top