Python selenium proxy server

Running Selenium Webdriver with a proxy in Python

I am trying to run a Selenium Webdriver script in Python to do some basic tasks. I can get the robot to function perfectly when running it through the Selenium IDE inteface (ie: when simply getting the GUI to repeat my actions). However when I export the code as a Python script and try to execute it from the command line, the Firefox browser will open but cannot ever access the starting URL (an error is returned to command line and the program stops). This is happening me regardless of what website etc I am trying to access. I have included a very basic code here for demonstration purposes. I don’t think that I have included the proxy section of the code correctly as the error being returned seems to be generated by the proxy. Any help would be hugely appreciated. The below code is simply meant to open www.google.ie and search for the word «selenium». For me it opens a blank firefox browser and stops.

from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import Select from selenium.common.exceptions import NoSuchElementException import unittest, time, re from selenium.webdriver.common.proxy import * class Testrobot2(unittest.TestCase): def setUp(self): myProxy = "http://149.215.113.110:70" proxy = Proxy(< 'proxyType': ProxyType.MANUAL, 'httpProxy': myProxy, 'ftpProxy': myProxy, 'sslProxy': myProxy, 'noProxy':''>) self.driver = webdriver.Firefox(proxy=proxy) self.driver.implicitly_wait(30) self.base_url = "https://www.google.ie/" self.verificationErrors = [] self.accept_next_alert = True def test_robot2(self): driver = self.driver driver.get(self.base_url + "/#gs_rn=17&gs_ri=psy-ab&suggest=p&cp=6&gs_id=ix&xhr=t&q=selenium&es_nrs=true&pf=p&output=search&sclient=psy-ab&oq=seleni&gs_l=&pbx=1&bav=on.2,or.r_qf.&bvm=bv.47883778,d.ZGU&fp=7c0d9024de9ac6ab&biw=592&bih=665") driver.find_element_by_id("gbqfq").clear() driver.find_element_by_id("gbqfq").send_keys("selenium") def is_element_present(self, how, what): try: self.driver.find_element(by=how, value=what) except NoSuchElementException, e: return False return True def is_alert_present(self): try: self.driver.switch_to_alert() except NoAlertPresentException, e: return False return True def close_alert_and_get_its_text(self): try: alert = self.driver.switch_to_alert() alert_text = alert.text if self.accept_next_alert: alert.accept() else: alert.dismiss() return alert_text finally: self.accept_next_alert = True def tearDown(self): self.driver.quit() self.assertEqual([], self.verificationErrors) if __name__ == "__main__": unittest.main() 

17 Answers 17

Works for me this way (similar to @Amey and @user4642224 code, but shorter a bit):

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) 

Источник

Читайте также:  Все команды языка программирования питон

Using Proxies With Python Selenium

Selenium is a powerful browser automation library that allows you to build bots and scrapers that can load and interact with web pages in the browser. As a result, Selenium is very popular amongst the Python web scraping community.

In this guide for The Python Selenium Web Scraping Playbook, we will look at how to integrate proxies into our Python Selenium based web scraper.

There are number of different types of proxies which you need to integrate differently with Selenium, so we will walk through how to integrate each type:

Using Proxies With Selenium​

The first and simplest type of proxy to integrate with Python Selenium are simple HTTP proxies (in the form of a IP address) that don’t require authentication. For example:

Depending on which type of browser you are using the integration method is slightly different.

Integrating Proxy With Selenium Chrome Browser​

To integrate this proxy IP into a Selenium scraper that uses a Chrome Browser we just need to set the —proxy-server arguement in our WebDriver options:

  from selenium import webdriver  ## Example Proxy PROXY = "11.456.448.110:8080"  ## Create WebDriver Options to Add Proxy chrome_options = WebDriver.ChromeOptions() chrome_options.add_argument(f'--proxy-server=PROXY>') chrome = webdriver.Chrome(chrome_options=chrome_options)  ## Make Request Using Proxy chrome.get("http://httpbin.org/ip") 

Now when we run the script we can see that Selenium is using the defined proxy IP:

Integrating Proxy With Selenium Firefox Browser​

To integrate this proxy IP into a Selenium scraper that uses a FireFox Browser we need to use the Proxy and ProxyType classes from the Selenium Webdriver library:

  from selenium import webdriver from selenium.webdriver.common.proxy import Proxy, ProxyType  ## Define Proxy proxy = Proxy(  'proxyType': ProxyType.MANUAL, 'httpProxy': "11.456.448.110:8080", 'noProxy': '' >)  ## Create Driver firefox_driver = webdriver.Firefox(proxy = proxy, executable_path=r"/root/geckodriver")  ## Make Request Using Proxy firefox_driver.get("http://httpbin.org/ip") 

Now when we run the script we can see that Selenium is using the defined proxy IP:

HTTP Proxy Authentication

This method works fine when you don’t need to add an authentication username and password to the proxy. We will look at how to use authenticated proxies in another section.

Using Authenticated Proxies With Selenium​

The above method doesn’t work if you need to use proxies that require username and password authentication.

It is very common for commercial proxy providers to sell access to their proxy pools by giving you single proxy endpoint that you send your requests too and authenticate your account using a username and password .

  "http://USERNAME:PASSWORD@proxy-server:8080" 

There are a couple ways to solve this, but one of the easiest is to use the Selenium Wire extension which makes it very easy to use proxies with Selenium.

First, you need to install Selenium Wire using pip:

Then update your scraper to use the seleniumwire webdriver instead of the default selenium webdriver :

from seleniumwire import webdriver from webdriver_manager.chrome import ChromeDriverManager ## Define Your Proxy Endpoints proxy_options = ‘proxy’: ‘http’: ‘http://USERNAME:PASSWORD@proxy-server:8080’, ‘https’: ‘http://USERNAME:PASSWORD@proxy-server:8080’, ‘no_proxy’: ‘localhost:127.0.0.1’ > > ## Set Up Selenium Chrome driver driver = webdriver.Chrome(ChromeDriverManager().install(), seleniumwire_options=proxy_options) ## Send Request Using Proxy driver.get(‘http://httpbin.org/ip’)

Now when we run the script we can see that Selenium is using a proxy IP:

Selenium Wire has a lot of other powerful functionality, so if you would like to learn more then check out our full Selenium Wire guide here.

Integrating Proxy APIs​

Over the last few years there has been a huge surge in proxy providers that offer smart proxy solutions that handle all the proxy rotation, header selection, ban detection and retries on their end. These smart APIs typically provide their proxy services in a API endpoint format.

However, these proxy API endpoints don’t integrate well with headless browsers when the website is using relative links as Selenium will try to attach the relative URL onto the proxy API endpoint not the websites root URL. Resulting, in some pages not loading correctly.

As a result, when integrating your Selenium scrapers it is recommended that you use their proxy port integration over the API endpoint integration when they provide them (not all do have a proxy port integration).

For example, in the case of the ScrapeOps Proxy Aggregator we offer a proxy port integration for situations like this.

The proxy port integration is a light front-end for the API and has all the same functionality and performance as sending requests to the API endpoint but allow you to integrate our proxy aggregator as you would with any normal proxy.

The following is an example of how to integrate the ScrapeOps Proxy Aggregator into your Selenium scraper using

from seleniumwire import webdriver from webdriver_manager.chrome import ChromeDriverManager SCRAPEOPS_API_KEY = ‘APIKEY’ ## Define ScrapeOps Proxy Port Endpoint proxy_options = ‘proxy’: ‘http’: f’http://scrapeops:SCRAPEOPS_API_KEY>@proxy.scrapeops.io:5353′, ‘https’: f’http://scrapeops:SCRAPEOPS_API_KEY>@proxy.scrapeops.io:5353′, ‘no_proxy’: ‘localhost:127.0.0.1’ > > ## Set Up Selenium Chrome driver driver = webdriver.Chrome(ChromeDriverManager().install(), seleniumwire_options=proxy_options) ## Send Request Using ScrapeOps Proxy driver.get(‘http://quotes.toscrape.com/’)

Full integration docs for Python Selenium and the ScrapeOps Proxy Aggregator can be found here.

To use the ScrapeOps Proxy Aggregator, you first need an API key which you can get by signing up for a free account here which gives you 1,000 free API credits.

More Web Scraping Tutorials​

So that’s how you can use both authenticated and unauthenticated proxies with Selenium to scrape websites without getting blocked.

If you would like to learn more about Web Scraping with Selenium, then be sure to check out The Selenium Web Scraping Playbook.

Or check out one of our more in-depth guides:

Источник

Оцените статью