python+selenium如何调用IEDriver添加代理

前言

对于一个合格的爬虫来说,代理IP是不可缺少的组成部分。说来惭愧,我们公司一些基于IEDriver的爬虫在很长一段时间中都是在没有使用代理的状态下运行的。给IE浏览器配置代理的常规方法设置的是全局代理,势必会影响到运行在同一台机器上的不同爬虫进程,而我们没有找到能够给IEDriver配置单进程代理的方法,相对而言ChromeDriver就省心很多了。
关于IEDriver的使用以及代理设置的资料在中文社区比较稀缺,我也是在Github上翻找后,终于找到了一些线索,特此分享。

环境

  1. Python2.7
  2. Selenium3.6.0
  3. IEDriver3.6.0
  4. IE11.0.96

实现

要对IEDriver配置单进程代理很简单,只需要设置UsePerProcessProxy=True即可,其他更多的配置内容可以查看https://github.com/SeleniumHQ/selenium/wiki/DesiredCapabilities

接下来是代码

from selenium import webdriver
from selenium.webdriver import DesiredCapabilities
from selenium.webdriver.ie.options import Options


def get_ie_browser(proxy):
    """ Get IE Browser """
    capabilities = DesiredCapabilities.INTERNETEXPLORER.copy()
    ie_option = Options()
    ie_option.use_per_process_proxy = True
    ie_option.browser_attach_timeout = 10000  # 10秒,IE实例启动超时时间
    proxy_option = {
        'proxyType': 'manual',
        'httpProxy': proxy,
        'sslProxy': proxy
    }
    capabilities['proxy'] = proxy_option  # 配置代理
    browser = webdriver.Ie(IE_DRIVER_PATH, capabilities=capabilities, ie_options=ie_option)
    browser.maximize_window()
    return browser

其中IE_DRIVER_PATH是IEDriver的本地路径,proxy的格式如http://111.111.111.111:2333,按照文档表示格式应为hostname.com:1234,可以不加协议名,但是我试验不加协议名的话似乎代理设置不能生效。

proxy_option的选项包括:

Key Type Description
proxyType string 必要参数,direct-直接连接,也就是不用代理;manual-手动设置代理;pac-通过一个url自动完成代理配置;autodetect-自动检测代理;system-使用系统设置
proxyAutoconfigUrl string 当proxyType为pac时可选,代理配置url
ftpProxy, httpProxy, sslProxy, socksProxy string (可选,如果proxyType != manual则忽略)分别指定FTP、HTTP、HTTPS和SOCKS请求使用的代理。如果proxyType是manual,则不定义特定协议的代理。期望格式示例:hostname.com:1234
socksUsername string (可选,如果proxyType != manual并且没有配置socksProxy则忽略)SOCKS代理用户名
socksPassword string (可选,如果proxyType != manual并且没有配置socksProxy则忽略)SOCKS代理密码
noProxy string (可选,如果proxyType != manual则忽略) specifies proxy bypass addresses. Format is driver specific.

水平有限,对于noProxy不太理解,不过一般情况下只用配置proxyType, httpProxy, sslProxy就行了。必要的话可以查看文档原文,也就是上述github链接。

你可能感兴趣的:(python,爬虫)