使用 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)
最常用的应用场景是设置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"')
修改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)
更多实验参数请参考chromedriver 官网
添加扩展
from selenium import webdriver
options = webdriver.ChromeOptions()
extension_path = '/extension/path'
options.add_extension(extension_path)
driver = webdriver.Chrome(chrome_options = options)
附赠添加代理方法
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)