selenium 定製啟動 chrome 的選項_selenium

來源:互聯網
上載者:User

使用 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)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.