【问题标题】:Unable to disable downloading images in headless mode for Selenium Chrome WebDriver using Python3无法使用 Python3 禁用 Selenium Chrome WebDriver 在无头模式下下载图像
【发布时间】:2020-02-10 12:29:46
【问题描述】:

我试图禁止我的驱动程序在网站上加载/下载图像。它应该会提高速度并减少加载站点所需的时间,因为不会下载图像,我仍然希望能够找到元素并与它们进行交互,例如发送键和单击。答案在这里How to disable CSS in Python selenium using ChromeOptions DOES 不回答我的问题,因为它会禁用一切。我无法与元素交互。这违背了硒的目的,因为我只能使用请求。

这是我所有的导入以供参考。

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

我可以在使用以下代码运行常规驱动程序时禁用图像。

option = Options()
chrome_prefs = {}
option.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"images": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"images": 2}
option.add_argument("--start-maximized")
option.add_argument('window-size=1680,941')
driver = webdriver.Chrome(options=option,executable_path='path')
driver.get('https://yahoo.com/')

当我转到“yahoo.com”时,没有加载/下载任何图像,如此屏幕截图https://imgur.com/a/cj2ylco所示

当我使用相同的代码但添加“无头”行时,它会加载图像。

option = Options()
chrome_prefs = {}
option.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"images": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"images": 2}
option.add_argument("--start-maximized")
option.add_argument('window-size=1680,941')
option.headless = True
driver = webdriver.Chrome(options=option,executable_path='path')
driver.get('https://yahoo.com/')
driver.save_screenshot('screen_shot2.png')

驱动程序仍会加载此屏幕截图中看到的图像https://imgur.com/a/krBpVCx 有什么解决办法吗?谢谢!

【问题讨论】:

  • 你能链接一个有效的答案吗?我查看了很多解决方案,但没有一个对我有用
  • 答案不起作用,因为我现在无法点击按钮,在非无头模式之前我仍然可以点击按钮
  • 无头模式没有前端。

标签: python-3.x selenium selenium-webdriver selenium-chromedriver


【解决方案1】:

试试

option = webdriver.ChromeOptions()
chrome_prefs = {}
option.experimental_options["prefs"] = chrome_prefs
chrome_prefs["profile.default_content_settings"] = {"images": 2}
chrome_prefs["profile.managed_default_content_settings"] = {"images": 2}
option.headless = True
driver = webdriver.Chrome("chromedriver.exe", options=option)

driver.get("https://google.com/")

上面的代码对我有用。

option.headless = True        ## this does the trick.

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 2023-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-12-18
    • 2022-09-23
    相关资源
    最近更新 更多