码迷,mamicode.com
首页 > 其他好文 > 详细

selenium 定制启动 chrome 的选项

时间:2017-02-09 11:07:44      阅读:6644      评论:0      收藏:0      [点我收藏+]

标签:ber   lan   alt   ges   get   github   调试器   官网   src   

使用 selenium 时,我们可能需要对 chrome 做一些特殊的设置,以完成我们期望的浏览器行为,比如阻止图片加载阻止JavaScript执行 等动作。这些需要 selenium的 ChromeOptions 来帮助我们完成

什么是 chromeoptions

chromeoptions 是一个方便控制 chrome 启动时属性的类。通过 selenium 的源码,可以看到,chromeoptions 主要提供如下的功能:

  • 设置 chrome 二进制文件位置 (binary_location)
  • 添加启动参数 (add_argument)
  • 添加扩展应用 (add_extension, add_encoded_extension)
  • 添加实验性质的设置参数 (add_experimental_option)
  • 设置调试器地址 (debugger_address)

定制启动选项

我们最常用的是三个功能

  • 添加chrome启动参数
  • 修改chrome设置
  • 添加扩展应用

下面以python为例一一说明,其他语言可以参考 selenium 源码

添加 chrome 启动参数

# 启动时设置默认语言为中文 UTF-8
from selenium import webdriver
options = webdriver.ChromeOptions()
options.add_argument(‘lang=zh_CN.UTF-8‘)
driver = webdriver.Chrome(chrome_options = options)
  • 1
  • 2
  • 3
  • 4
  • 5

最常用的应用场景是设置user-agent以用来模拟移动设备,比如模拟 iphone6

options.add_argument(‘user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"‘)
  • 1

修改chrome设置

# 禁止图片加载
from selenium import webdriver
options = webdriver.ChromeOptions()
prefs = {
    ‘profile.default_content_setting_values‘ : {
        ‘images‘ : 2
    }
}
options.add_experimental_option(‘prefs‘,prefs)
driver = webdriver.Chrome(chrome_options = options)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

更多实验参数请参考chromedriver 官网

添加扩展

from selenium import webdriver
options = webdriver.ChromeOptions()
extension_path = ‘/extension/path‘
options.add_extension(extension_path)
driver = webdriver.Chrome(chrome_options = options)
  • 1
  • 2
  • 3
  • 4
  • 5

附赠添加代理方法

from selenium import webdriver
PROXY = "proxy_host:proxy:port"
options = webdriver.ChromeOptions()
desired_capabilities = options.to_capabilities()
desired_capabilities[‘proxy‘] = {
    "httpProxy":PROXY,
    "ftpProxy":PROXY,
    "sslProxy":PROXY,
    "noProxy":None,
    "proxyType":"MANUAL",
    "class":"org.openqa.selenium.Proxy",
    "autodetect":False
}
driver = webdriver.Chrome(desired_capabilities = desired_capabilities)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
技术分享
 
 

转http://blog.csdn.net/vinson0526/article/details/51850929

selenium 定制启动 chrome 的选项

标签:ber   lan   alt   ges   get   github   调试器   官网   src   

原文地址:http://www.cnblogs.com/lgh344902118/p/6380786.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!