python webdriver + proxy

How to use selenium webdriver chromedriver with proxy?


from pyvirtualdisplay import Display
from selenium import webdriver

# run display
# this line is for avoid duplicated displays
os.environ['DISPLAY'] = ':99'
display = Display(visible=0, size=(800, 600))
display.start()

# prepare driver 
driver = settings.BASE_DIR + "/app/lib/chromedriver"
os.environ["webdriver.chrome.driver"] = driver

# prepare configuration
cfg = ProxyService.get_config()

# proxy config as string
proxy = "%s:%s" % (cfg['domain'], cfg['port'])
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--proxy-server=%s' % proxy)
# do not load images
prefs = {"profile.managed_default_content_settings.images": 2}
chrome_options.add_experimental_option("prefs", prefs)

# run driver
driver = webdriver.Chrome(executable_path=driver, chrome_options=chrome_options)
driver.get(self.url)
result = driver.page_source
# close driver and display
driver.quit()
display.stop()