selenium webdriver 之 Chrome -headless set proxy 暨 自动化测试中无头谷歌浏览器设置代理

selenium webdriver 之 Chrome -headless set proxy 暨 自动化测试中无头谷歌浏览器设置代理

众所周知PhantomJS 很好用, 但是确实版本有点旧了。 直至今年Chrome/Firefox 终于有了正式的headless mode无头模式。就让我们探讨一下吧。

当我们使用Chrome 有头模式的时候,代理自然不是问题。
但是当我使用Chrome -headless 时发现,系统IE/CHROME 设置的代理却不生效。

找到selenium 官方文档有关proxy资料。并没有找到直接的例子。
文档中说道:CHROME PROXY 与 IE 是相似。但是到目前未知还没有实际例子。(当我撰写本文时,发现已经找不到该网址)

于是我参照IE例子有了:

# _*_ coding:utf‐8 _*

'''
@描述:chrome -headless with proxy -- baidu
@作者:wuyanhui
@版本:V1.0
@创建时间:2017/11/15 16:47
'''

from selenium import webdriver

# ---chrome
chrome_executable_path = r"E:\Program Files (x86)\wyhdriver\chromedriver.exe"
PROXY = "http://10.18.97.76:3128"

if __name__ == '__main__':


    # 配置项目
    # Create a copy of desired capabilities object.
    # 在windows系统:chrome driver 默认使用的是IE代理设置。而例如Firefox可以自行配置proxy
    desired_capabilities = webdriver.DesiredCapabilities.INTERNETEXPLORER.copy()
    # Change the proxy properties of that copy.
    desired_capabilities['proxy'] = {
        "httpProxy": PROXY,
        "ftpProxy": PROXY,
        "sslProxy": PROXY,
        "noProxy": None,
        "proxyType": "MANUAL",
        "class": "org.openqa.selenium.Proxy",
        "autodetect": False
    }

    # 创建的新实例驱动
    options = webdriver.ChromeOptions()
    options.add_argument('headless')
    # options.add_argument('window-size=1200x600')
    driver = webdriver.Chrome(executable_path=chrome_executable_path,chrome_options=options,desired_capabilities=desired_capabilities)

    # 尝试访问登陆页面
    for neti in range(0, 3):
        SUCCESS = True
        try:
            driver.get('http://www.baidu.com')
            driver.implicitly_wait(3)  # wait seconds 等待页面加载
        except Exception as e:
            SUCCESS = False
            print(e)
            continue
        if SUCCESS:
            break
    print(driver.page_source)
    print("--finish--")
    driver.quit()
    exit(0)

怎么样,可以了吧。如有问题可以留言共同学习呦。

  • 0
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值