selenium 定製啓動 chrome 的選項

使用 selenium 時,咱們可能須要對 chrome 作一些特殊的設置,以完成咱們指望的瀏覽器行爲,好比阻止圖片加載阻止JavaScript執行 等動做。這些須要 selenium的 ChromeOptions 來幫助咱們完成python

什麼是 chromeoptions

chromeoptions 是一個方便控制 chrome 啓動時屬性的類。經過 selenium 的源碼,能夠看到,chromeoptions 主要提供以下的功能:git

  • 設置 chrome 二進制文件位置 (binary_location)
  • 添加啓動參數 (add_argument)
  • 添加擴展應用 (add_extension, add_encoded_extension)
  • 添加實驗性質的設置參數 (add_experimental_option)
  • 設置調試器地址 (debugger_address)

定製啓動選項

咱們最經常使用的是三個功能github

  • 添加chrome啓動參數
  • 修改chrome設置
  • 添加擴展應用

下面以python爲例一一說明,其餘語言能夠參考 selenium 源碼web

添加 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以用來模擬移動設備,好比模擬 iphone6chrome

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)

轉http://blog.csdn.net/vinson0526/article/details/51850929iphone

相關文章
相關標籤/搜索