2019獨角獸企業重金招聘Python工程師標準>>>
使用 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)http://blog.csdn.net/vinson0526/article/details/51850929