序
使用 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-8from selenium import webdriveroptions = webdriver.ChromeOptions()options.add_argument('lang=zh_CN.UTF-8')driver = webdriver.Chrome(chrome_options = options)
最常執行的 App情境是設定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 webdriveroptions = 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 webdriveroptions = webdriver.ChromeOptions()extension_path = '/extension/path'options.add_extension(extension_path)driver = webdriver.Chrome(chrome_options = options)
附贈添加代理方法
from selenium import webdriverPROXY = "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)