在chromedriver中使用python绑定设置chrome.prefs

15 投票
5 回答
32668 浏览
提问于 2025-04-17 17:37

我今天一直在找这个问题,似乎目前在Python的chromedriver实现中没有现成的解决方案。

我想知道怎么通过webdriver.Chrome()方法设置特定的chrome.prefs(比如一些配置,比如profile.managed_default_content_settings.images = 2)。

我已经尝试过用webdriver.ChromeOptions(),但没有成功。在Java中有合适的函数可以做到这一点。

但是在Python中呢?我现在正在做的是这个……

    options = webdriver.ChromeOptions()
    options.add_argument('--allow-running-insecure-content')
    options.add_argument('--disable-web-security')
    options.add_argument('--disk-cache-dir=/var/www/cake2.2.4/app/tmp/cache/selenium-chrome-cache')
    options.add_argument('--no-referrers')
    options.add_argument('--window-size=1003,719')
    options.add_argument('--proxy-server=localhost:8118')
    options.add_argument("'chrome.prefs': {'profile.managed_default_content_settings.images': 2}")


    self.selenium = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver',chrome_options=options)

5 个回答

4

这是在最新的chromedriver版本中有效的,至少从2.15到当前的2.20版本:

chrome_options = Options()
chrome_options.add_experimental_option( "prefs", {'profile.managed_default_content_settings.images': 2})
chrome = webdriver.Chrome('/path/to/chromedriver',chrome_options=chrome_options)
chrome.get("https://google.com")
7

给大家一个小更新,特别是那些在这个问题上遇到困难的人。

对于较新的版本,下面的代码可以顺利运行,没有问题:

options.add_experimental_option('prefs', {'download.default_directory':'C:\\temp'})
9

如果你想在chromedriver中禁用图片,可以试试下面的代码。

from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option( "prefs", {'profile.default_content_settings.images': 2})
driver = webdriver.Chrome(chrome_options=chrome_options)

撰写回答