Disable images in Selenium Google ChromeDriver - c#

How does one disable images in Google chrome when using it through Selenium and c#?
I've attempted 6 ways and none worked. I've even tried the answer on this StackOverflow question, however I think the info in it is out of date.
Chrome driver: V2.2
Chrome version: V29.0.1547.66 m
Selenium: V2.35
All the attempts I've made don't cause exceptions, they run normally but still display images:
Attempt 1:
ChromeOptions co = new ChromeOptions();
co.AddArgument("--disable-images");
IWebDriver driver = new ChromeDriver(co);
Attempt 2:
DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
capabilities.SetCapability("chrome.switches", new string[1] { "disable-images" });
Attempt 3:
ChromeOptions co = new ChromeOptions();
co.AddAdditionalCapability("chrome.switches", new string[1] { "disable-images" });
Attempt 4:
var imageSetting = new Dictionary<string, object>();
imageSetting.Add("images", 2);
Dictionary<string, object> content = new Dictionary<string, object>();
content.Add("profile.default_content_settings", imageSetting);
var prefs = new Dictionary<string, object>();
prefs.Add("prefs", content);
var options = new ChromeOptions();
var field = options.GetType().GetField("additionalCapabilities", BindingFlags.Instance | BindingFlags.NonPublic);
if (field != null)
{
var dict = field.GetValue(options) as IDictionary<string, object>;
if (dict != null)
dict.Add(ChromeOptions.Capability, prefs);
}
Attempt 5:
ChromeOptions options = new ChromeOptions();
options.AddAdditionalCapability("profile.default_content_settings", 2);
Attempt 6:
Dictionary<String, Object> contentSettings = new Dictionary<String, Object>();
contentSettings.Add("images", 2);
Dictionary<String, Object> preferences = new Dictionary<String, Object>();
preferences.Add("profile.default_content_settings", contentSettings);
DesiredCapabilities caps = DesiredCapabilities.Chrome();
caps.SetCapability("chrome.prefs", preferences);

This is my solution
IWebDriver driver;
ChromeOptions options = new ChromeOptions();
options.AddUserProfilePreference("profile.default_content_setting_values.images", 2);
driver = new ChromeDriver(options);

You should use --blink-settings instead of --disable-images by:
options.add_argument('--blink-settings=imagesEnabled=false')
which also works in headless mode. Setting profile doesn't work in headless mode. You can verify it by screenshot:
driver.get_screenshot_as_file('headless.png')
Note: I was using python with selenium, but I think it should be easy to transfer to c#.

For your method 1-3, I don't see a Chrome switch called --disable-images listed here. So even if the code snippets are correct, they won't work no matter what. Where did you get that switch? Any references?
For the methods 4-6, I assume you got the idea from this chromdriver issue. I don't know if this {'profile.default_content_settings': {'images': 2}} is still valid or not, but you can give it a try with the following code (which was originally the answer to How to set Chrome preferences using Selenium Webdriver .NET binding?, answer provided by Martin Devillers).
public class ChromeOptionsWithPrefs: ChromeOptions {
public Dictionary<string,object> prefs { get; set; }
}
public static void Initialize() {
var options = new ChromeOptionsWithPrefs();
options.prefs = new Dictionary<string, object> {
{ "profile.default_content_settings", new Dictionary<string, object>() { "images", 2 } }
};
var driver = new ChromeDriver(options);
}

Use http://chrome-extension-downloader.com/ to download the "Block Image" extension (https://chrome.google.com/webstore/detail/block-image/pehaalcefcjfccdpbckoablngfkfgfgj?hl=en-GB). The extension prevents the image from being downloaded in the first place. Now it's just a matter of loading it using the following statement:
var options = new ChromeOptions();
//use the block image extension to prevent images from downloading.
options.AddExtension("Block-image_v1.0.crx");
var driver = new ChromeDriver(options);

An easier approach would be solely:
ChromeOptions options = new ChromeOptions();
options.addArguments("headless","--blink-settings=imagesEnabled=false");

I found out simple solution. This idea referred from Python:Disable images in Selenium Google ChromeDriver
var service = ChromeDriverService.CreateDefaultService(#WebDriverPath);
var options = net ChromeOptions();
options.AddUserProfilePreference("profile.managed_default_content_settings.images", 2);
IWebDriver Driver = new ChromeDriver(service, options);

I recommend that you create a new profile, customize this profile so that it does not load the images, and use this profile as a chromeOption to set up your driver.
See: this article

Related

OpenQA.Selenium.WebDriverException: 'Unexpected server error.' using EdgeOptions

I am trying to run a test using the W3C spec of Selenium WebDriver with C#.
This is my code which I believe is correct based on reading the W3C docs here.
[Test]
public void SimpleSelenium4Example()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
var options = new EdgeOptions()
{
BrowserVersion = "latest",
PlatformName = "Windows 10"
};
var sauceOptions = new JObject
{
["username"] = sauceUserName,
["accessKey"] = sauceAccessKey,
["name"] = TestContext.CurrentContext.Test.Name
};
options.AddAdditionalCapability("sauce:options", sauceOptions.ToString());
Driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
Driver.Navigate().GoToUrl("https://www.google.com");
Assert.Pass();
}
I get this error OpenQA.Selenium.WebDriverException: 'Unexpected server error.' when instantiating the RemoteWebDriver.
Not sure what the problem is. Any help is appreciated.
The .NET bindings serialize the objects appropriately; there's no need to attempt to use the Json.NET API at all (as your use of JObject implies you are), and serializing the JSON object (using ToString()) before transmission over the wire is likely to be unsuccessful.
[Test]
public void SimpleSelenium4Example()
{
//TODO please supply your Sauce Labs user name in an environment variable
var sauceUserName = Environment.GetEnvironmentVariable("SAUCE_USERNAME", EnvironmentVariableTarget.User);
//TODO please supply your own Sauce Labs access Key in an environment variable
var sauceAccessKey = Environment.GetEnvironmentVariable("SAUCE_ACCESS_KEY", EnvironmentVariableTarget.User);
var options = new EdgeOptions()
{
BrowserVersion = "latest",
PlatformName = "Windows 10"
};
var sauceOptions = new Dictionary<string, object>();
sauceOptions["username"] = sauceUserName;
sauceOptions["accessKey"] = sauceAccessKey;
sauceOptions["name"] = TestContext.CurrentContext.Test.Name;
options.AddAdditionalCapability("sauce:options", sauceOptions);
Driver = new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
Driver.Navigate().GoToUrl("https://www.google.com");
Assert.Pass();
}

Disabling a popup

I am trying to Disable a popup which keeps showing up, which is a "Chrome Extension".
I am attaching a screenshot and also the code.
What I am trying to do is I want to click the Disable button.
The code I am using is:
public static void Initialize()
{
//Instance = new FirefoxDriver();
//Instance = new InternetExplorerDriver(#"C:\Sele2");
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-popup-blocking");
var basePath = AppDomain.CurrentDomain.BaseDirectory;
Instance = new ChromeDriver(basePath, options);
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
}
Can someone please help? Thanks in advance
You can add one more arguments as --disable-extensions in your chrome options as below :-
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-popup-blocking","--disable-extensions");
var basePath = AppDomain.CurrentDomain.BaseDirectory;
Instance = new ChromeDriver(basePath, options);
Instance.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));

Cannot pass DesiredCapabilities to ChromeDriver:s constructor?

When I try to use
var dc = DesiredCapabilities.Chrome();
var driver = new ChromeDriver(dc);
I get "Cannot resolve constructor".
It seems like I have to pass ChromeOptions instead.
Why?
Every single tutorial/help page on the subject suggests that I pass DesiredCapabilities.
I am using Selenium.WebDriver.ChromeDriver version 2.21.0.0.
You can use ChromeOptions to set any specific options.
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArguments("--start-maximized");
options.ToCapabilities();
ChromeDriverService service = ChromeDriverService.CreateDefaultService(Environment.GetEnvironmentVariable("USERPROFILE") + "\\Downloads");
IWebDriver chromeDriver = new ChromeDriver(service, options);
You can use- options.ToCapabilities(); to get see the capabilities.
You can use ChromeOptions to set any specific type of capabilities- peter.sh/experiments/chromium-command-line-switches . It seems the DesiredCapabilities can be added only in Java or if you are dealing with InternetExplorerDriver- Selenium c#: How to launch Internet Explorer driver in a specific version (IE8 for example)
Using dotpeek and looking at the chromedriver constructors (which there are 7 overloads) 6 of them invoke the constructor below on the ChromeDriver itself
public ChromeDriver(ChromeDriverService service, ChromeOptions options, TimeSpan commandTimeout)
: base((ICommandExecutor) new DriverServiceCommandExecutor((DriverService) service, commandTimeout), ChromeDriver.ConvertOptionsToCapabilities(options))
{
}
Which in turn calls the base constructor on the RemoteWebdriver. This passes in the last parameter as ChromeDriver.ConvertOptionsToCapabilities(options)
Looking at the you can see this:
private static ICapabilities ConvertOptionsToCapabilities(ChromeOptions options)
{
if (options == null)
throw new ArgumentNullException("options", "options must not be null");
return options.ToCapabilities();
}
Then into options.ToCapabilities:
public override ICapabilities ToCapabilities()
{
Dictionary<string, object> dictionary = this.BuildChromeOptionsDictionary();
DesiredCapabilities desiredCapabilities = DesiredCapabilities.Chrome();
desiredCapabilities.SetCapability(ChromeOptions.Capability, (object) dictionary);
if (this.proxy != null)
desiredCapabilities.SetCapability(CapabilityType.Proxy, (object) this.proxy);
Dictionary<string, object> preferencesDictionary = this.GenerateLoggingPreferencesDictionary();
if (preferencesDictionary != null)
desiredCapabilities.SetCapability(CapabilityType.LoggingPreferences, (object) preferencesDictionary);
foreach (KeyValuePair<string, object> additionalCapability in this.additionalCapabilities)
desiredCapabilities.SetCapability(additionalCapability.Key, additionalCapability.Value);
You can see under the hood it appears its already using DesiredCapabilities.Chrome() and you don't need to pass it in. Perhaps the tutorials you have seen are outdated?

Pass to chromedriver capabilities as desiredCapabilities c#

I have software which does automated testing via chrome browser, but now this program failed with error message "Vector smash protection is enabled."
I've found a solution for this case, but this solution implemented via java API.
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--incognito"));
ChromeOptions options = new ChromeOptions();
options.addArguments("test-type");
WebDriver driver = new ChromeDriver(capabilities);
How to implement a code the same as above via c#?
You need a Dictionary
// Capabilities Values
var imageSetting = new Dictionary<string, object> {{"images", 2}};
var content = new Dictionary<string, object> {{"profile.default_content_settings", imageSetting}};
var prefs = new Dictionary<string, object> {{"prefs", content}};
// List of Chromium Command Line Switches
var options = new ChromeOptions();
options.AddArguments(
"--disable-extensions",
"--disable-features",
"--disable-popup-blocking",
"--disable-settings-window");
// Add the Capabilities
var field = options.GetType().GetField("additionalCapabilities", BindingFlags.Instance | BindingFlags.NonPublic);
if (field != null)
{
var dict = field.GetValue(options) as IDictionary<string, object>;
if (dict != null) dict.Add(ChromeOptions.Capability, prefs);
}
// Create the Chrome Driver
var chromeDriver = new ChromeDriver(options);
Also you can send the driver path when you create the ChromeDriver object.

Disable images in Selenium ChromeDriver

Trying to disable images loading in ChromeDriver. I'm using the following code, however it's still loading the images. Any suggestions?
DesiredCapabilities capabilities = DesiredCapabilities.Chrome();
capabilities.SetCapability("chrome.switches", new string[1] { "disable-images" });
IWebDriver driver = new ChromeDriver(#"C:\chromedriver\", capabilities);
I had the same problem and I found the answer here;
Map<String, Object> contentSettings = new HashMap<String, Object>();
contentSettings.put("images", 2);
Map<String, Object> preferences = new HashMap<String, Object>();
preferences.put("profile.default_content_settings", contentSettings);
DesiredCapabilities caps = DesiredCapabilities.chrome();
caps.setCapability("chrome.prefs", preferences);

Categories