How to run Selenium Webdriver with a proxy in Python?

Sometimes, we want to run Selenium Webdriver with a proxy in Python.

In this article, we’ll look at how to run Selenium Webdriver with a proxy in Python.

How to run Selenium Webdriver with a proxy in Python?

To run Selenium Webdriver with a proxy in Python, we can use the Proxy class.

For instance, we write

from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType

prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = "ip_addr:port"
prox.socks_proxy = "ip_addr:port"
prox.ssl_proxy = "ip_addr:port"

capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)

driver = webdriver.Chrome(desired_capabilities=capabilities)

to create a Proxy object.

Then we set the proxy settings for various protocols with

prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = "ip_addr:port"
prox.socks_proxy = "ip_addr:port"
prox.ssl_proxy = "ip_addr:port"

Next, we add the Proxy object to the capabilities with

prox.add_to_capabilities(capabilities)

And then we create the Chrome driver with the capabilities with

driver = webdriver.Chrome(desired_capabilities=capabilities)

to set the proxy settings when starting Chrome.

Conclusion

To run Selenium Webdriver with a proxy in Python, we can use the Proxy class.