简体   繁体   English

阻止在 Selenium 无头 Chrome [python] 上下载图像

[英]Block the download of images on Selenium headless Chrome [python]

The following two python codes block the download of images on selenium non-headless chrome, ie in the saved screenshots the images are not visible.以下两个 python 代码阻止在 selenium 非无头 chrome 上下载图像,即在保存的屏幕截图中图像不可见。 If we uncomment the two commented lines the codes don't work anymore as expected though, that is images are visible in the screenshots saved by the headless chrome browser.如果我们取消注释这两条注释行,代码将不再按预期工作,即图像在无头 chrome 浏览器保存的屏幕截图中可见。 How to properly block images from loading in the headless chrome on selenium for python?如何正确阻止图像加载到 python 的 selenium 上的无头 chrome 中?

First method第一种方法

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("prefs", {"profile.default_content_settings.images": 2})
chrome_options.add_experimental_option("prefs", {"profile.managed_default_content_settings.images": 2})
# chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options = chrome_options, executable_path = ChromeDriverManager().install())

driver.get('https://www.hdblog.it/page/1/')
driver.save_screenshot('screenshot.png')

second method第二种方法

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

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(options=option, executable_path = ChromeDriverManager().install())

driver.get('https://www.hdblog.it/page/1/')
driver.save_screenshot('screenshot.png')

preference is not supported for headless browser无头浏览器不支持首选项

As of Feb, 2021截至 2021 年 2 月

https://bugs.chromium.org/p/chromedriver/issues/detail?id=1925 https://bugs.chromium.org/p/chromedriver/issues/detail?id=1925

Headless chrome doesn't support preferrences setting. Headless chrome 不支持首选项设置。 You can use command line arguments only.您只能使用命令行 arguments。

the full list of supported arguments are:支持的 arguments 的完整列表是:

https://peter.sh/experiments/chromium-command-line-switches/https://peter.sh/experiments/chromium-command-line-switches/

Here you can see --blink-settings so,在这里你可以看到 --blink-settings 所以,

try尝试

chrome_options.add_arguments('--blink-settings=imagesEnabled=false')

full blink settings can be accessed here:可以在此处访问完整的闪烁设置:

https://chromium.googlesource.com/chromium/blink/+/master/Source/core/frame/Settings.in https://chromium.googlesource.com/chromium/blink/+/master/Source/core/frame/Settings.in

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM