selenium 定制启动 Chrome 的选项

转载自 blog.csdn.net/vinson0526/article/details/51850929  侵删

使用selenium时,我们可能需要对chrome做一些特殊的设置,以完成我们期望的浏览器行为,比如阻止图片加载,阻止JavaScript执行等动作。

这些需要 selenium的 ChromeOptions 来帮助我们完成

什么是 chromeoptions

chromeoptions是一个方便控制chrome启动时属性的类。通过selenium的源码,可以看到,chromeoptions主要提供如下的功能:

1.设置 chrome 二进制文件位置 (binary_location)

2.添加启动参数 (add_argument)

3.添加扩展应用 (add_extension, add_encoded_extension)

4.添加实验性质的设置参数 (add_experimental_option)

5.设置调试器地址 (debugger_address)

定制启动选项

我们最常用的是三个功能

1.添加chrome启动参数

2.修改chrome设置

3.添加扩展应用

添加 chrome 启动参数

from selenium impor twebdriver

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设置

# 禁止图片加载fromseleniumimportwebdriver

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)

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容