Reputation: 57
Im trying to disable my driver from loading/downloading images on a website. It should increase speed and also decrease the amount of time it takes to load a site as images wouldn't be downloaded, I still want to be able to find elements and interact with them like sending keys and clicking. The answer located here How to disable CSS in Python selenium using ChromeOptions DOES not answer my question as it disables everything. Im unable to interact with elements. This defeats the purpose of selenium as I could just use requests.
Here is all my imports for reference.
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
Im able to disable images when running a regular driver using the following code.
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/')
No images are loaded/downloaded when I go to 'yahoo.com' as seen in this screenshot https://i.sstatic.net/RuWyt.jpg
When I use the same code but add the 'headless' line it loads images.
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')
The driver still loads the images as seen in this screenshot https://i.sstatic.net/j9ca5.jpg is there any fix out there for this? Thank you!
Upvotes: 1
Views: 1579
Reputation: 752
Try
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/")
Code above works for me.
option.headless = True ## this does the trick.
Upvotes: 1