Selenium Grid in C# - c#

I'm trying to run my tests in another local machine, but i always end up failing! I've seen videos implementing successfully in JAVA, but I'm trying to do it through c#.
Any Ideas are most appreciated!
public class Driver
{
public static IWebDriver Instance { get; set; }
public static void Initialize()
{
IWebDriver driver;
driver = new ChromeDriver();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.Chrome();
capabilities.SetCapability(CapabilityType.BrowserName, "chrome");
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
driver = new RemoteWebDriver(new Uri("http://localhost:4446/wd/hub"), capabilities);
}
public static void Close()
{
Instance.Dispose();
Instance = null;
}

You should use remote uri of your grid instance instead of local and ensure that you have chrome installed at least on one of your nodes. If you want to use selenium grid locally start local hub first using selenium-server-standalone.jar. You should use info from here
Also you don't need this code:
driver = new ChromeDriver();` - you need RemoteWebDriver directly
For me this code works perfectly:
var uri = 'uri_to_your_grid_hub';
var capabilities = new ChromeOptions().ToCapabilities();
var commandTimeout = TimeSpan.FromMinutes(5);
var driver = new RemoteWebDriver(new Uri(uri),capabilities,commandTimeout)

Related

Selenium Chrome does not add extensions and arguments

It looks like Selenium doesn't apply any options to the new browser instance, since neither the extension nor the arguments that were defined in code are applied, it just launches a regular Chrome window without extensions, with an infobar and no incognito mode
void ChromeSession()
{
const string siteUrl = "https://www.google.com/";
var options = new ChromeOptions();
options.AddArgument("--disable-infobars");
options.AddArgument("--incognito");
options.AddExtension(#"C:\Users\kiespetch1\Downloads\Solver.crx");
new DriverManager().SetUpDriver(new ChromeConfig());
var driver = new ChromeDriver();
driver.Url = siteUrl;
}
How I can add extensions and launch arguments?
You can add profiles
options.AddArgument = ("user-data-dir':'/Users/Application/Chrome/Default'}

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();
}

How do you set the port for ChromeDriver in Selenium?

As some background, I'm playing around with BrowserMob proxy and I am getting blocked by the port settings. So I'd like to know how to set a port by myself.
Server srv = new Server(#"C:\BMob\browsermob\bin\browsermob-proxy.bat");
srv.Start();
Client cln = srv.CreateProxy();
cln.NewHar("BOWZA");
ChromeOptions co = new ChromeOptions();
Proxy seleniumProxy = new Proxy { HttpProxy = cln.SeleniumProxy };
co.Proxy = seleniumProxy;
ChromeDriver cDriver = new ChromeDriver(co);
// What do I do now...?
I just failed to find anything documenting this, sorry
This should work:
ChromeDriverService service= ChromeDriverService.CreateDefaultService(DRIVER_PATH);
service.Port = <PORT>;
IWebDriver WebDriver = new ChromeDriver(service);
This works for me. I'm using webDriverManager as well
ChromeDriverService chromeDriverService = new ChromeDriverService.Builder().usingPort(DesiredPortNumber).build();
Then use it as a parameter when initializing new driver
new ChromeDriver(chromeDriverService , BrowserOptionsManager.getChromeOptions());

Unable to launch Chrome in incognito mode using Selenium WebDriver using C#

I am trying to launch Chrome using Selenium WebDriver in incognito mode, but not able to accomplish. I tried all options but not able to launch. Below is my code snippet
case "chrome":
ChromeOptions options = new ChromeOptions();
options.AddArgument("--incognito"); //Line XYZ
desiredCapabilities = DesiredCapabilities.Chrome();
desiredCapabilities.SetCapability(ChromeOptions.Capability, options);
break;
var capabilities = BuildDesiredCapabilities();
webDriver = new RemoteWebDriver(new Uri(gridHubURL), capabilities,
TimeSpan.FromSeconds(ApplicationConfiguration.RemoteDriverTimeOutValue));
Can anyone please help me what I am doing wrong here? I also tried the below code options in Line XYZ
Any pointers will be much helpful.
EDIT1
Please find the updated code here.
public IWebDriver CreateDriver()
{
var capabilities = BuildDesiredCapabilities();
webDriver = new RemoteWebDriver(new Uri(gridHubURL), capabilities,
TimeSpan.FromSeconds(ApplicationConfiguration.RemoteDriverTimeOutValue));
webDriver.Manage().Window.Maximize();
webDriver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(ApplicationConfiguration.TimeOutValue));
webDriver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(ApplicationConfiguration.TimeOutValue));
return webDriver;
}
private DesiredCapabilities BuildDesiredCapabilities()
{
DesiredCapabilities desiredCapabilities;
switch (browserName.ToLower())
{
case "firefox":
desiredCapabilities = DesiredCapabilities.Firefox();
break;
case "chrome":
desiredCapabilities = DesiredCapabilities.Chrome();
desiredCapabilities.SetCapability("chrome.switches", "--incognito");
break;
case "ie":
desiredCapabilities = DesiredCapabilities.InternetExplorer();
desiredCapabilities.SetCapability("ie.ensureCleanSession", true);
break;
default:
desiredCapabilities = DesiredCapabilities.Firefox();
break;
}
return desiredCapabilities;
}
The .NET bindings have introduced browser-specific Options classes to avoid having to know or understand arbitrary capability values. You were using just such a class, ChromeOptions, in your original code. You missed one extra step, though, in how to use the ChromeOptions class with RemoteWebDriver. The missing piece is that you should use the ToCapabilities() method to convert the ChromeOptions object to the ICapabilities object that RemoteWebDriver expects. Your code would look something like the following:
var options = new ChromeOptions();
options.AddArgument("incognito");
var capabilities = options.ToCapabilities();
var driver = new RemoteWebDriver(new URI(gridHubURL), capabilities);
You should pass parameters to the executable like this:
desiredCapabilities = DesiredCapabilities.Chrome();
desiredCapabilities.SetCapability("chrome.switches", "--incognito");
So passing the parameter --incognito to the chrome.switches capability should work.
NOTE:
The chrome.switches capability has been deprecated for over two years. A list of the current supported capabilities can be found at the official chromedriver Google Sites page. Additionally, use of arbitrary capabilities has been discouraged by the Selenium project for some time, particularly when using the .NET bindings

Disable images in Selenium Google ChromeDriver

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

Categories