C# implementation of RemoteWebDriver fails to install Chrome extension - c#

This ticket is related to ticket 1578 for Selenium , but my issue is with Chrome and not Firefox as in that ticket.
Installing and configuring an extension works when using a local driver. Doing the same using the C# implementation of RemoteWebDriver does not. Tested this with Chrome.
In my test case, the remote execution was done against SauceLabs. Contacted their support and they verified that installing extensions via RemoteWebDriver works in the JAVA implementation, but fails using the C# implementation.
To quote from their support ticket:
"I tried this myself and I was running into issues on my own end, so this may be a flaw with the C# Selenium bindings with RemoteWebDriver."
My code:
private IWebDriver GetSauceLabsDriver(){
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ChromeOptions options = new ChromeOptions();
options.AddExtensions(outPutDirectory + #"\3.1.3_0.crx");
//DesiredCapabilities caps = (DesiredCapabilities)options.ToCapabilities();
var caps = new DesiredCapabilities();
caps.SetCapability(ChromeOptions.Capability, options.Extensions[0]);
caps.SetCapability(CapabilityType.BrowserName, "chrome");
caps.SetCapability(CapabilityType.Version, "53.0");
caps.SetCapability(CapabilityType.Platform, "Windows 10");
caps.SetCapability("deviceName", "");
caps.SetCapability("deviceOrientation", "");
caps.SetCapability("username", "kin");
caps.SetCapability("accessKey", "9cd6-438e-a9635b70953d");
caps.SetCapability("name", TestContext.CurrentContext.Test.Name);
return new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), caps,
TimeSpan.FromSeconds(600));
}

This is a common mistake made by users of the .NET bindings. You should almost never be using the DesiredCapabilities class directly in your code. Rather, you should almost exclusively be using the ChromeOptions class to set all of the options before instantiaung the driver, and use the .ToCapabilitied() method to convert it to an ICapabilities object that can be used with the RemoteWebDriver constructor. In your specific case, that would look like this:
private IWebDriver GetSauceLabsDriver()
{
var outPutDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
ChromeOptions options = new ChromeOptions();
options.AddExtensions(outPutDirectory + #"\3.1.3_0.
// Add capabilities that belong at the top
// level of the capabilities object as opposed
// to part of the chromeOptions capability. Note
// that setting the browser name is entirely
// redundant and thus is not done. Likewise,
// deviceName and deviceOrientation are
options.AddAdditionalCapability(CapabilityType.Version, "53.0", true);
options.AddAdditionalCapability(CapabilityType.Platform, "Windows 10", true);
options.AddAdditionalCapability("username", "kin", true);
options.AddAdditionalCapability("accessKey", "9cd6-438e-a9635b70953d", true);
options.AddAdditionalCapability("name", TestContext.CurrentContext.Test.Name, true);
return new RemoteWebDriver(new Uri("http://ondemand.saucelabs.com:80/wd/hub"), options.ToCapabilities(),
TimeSpan.FromSeconds(600));
}

Related

Selenium Webdriver C# - redirect chromedriver.log to stdout or stderr

I'm trying to redirect Chromedriver logs from saving to chromedriver.log to stdout, as it's done in Geckodriver and MSEdgeDriver, so that I can view the logs in build logs of CI (TeamCity). As mentioned in the title, I'm using C# bindings. My current code is
private IWebDriver ResolveChromeDriver()
{
var service = ChromeDriverService.CreateDefaultService();
service.EnableVerboseLogging = true;
var options = new ChromeOptions();
options.SetLoggingPreference(LogType.Driver, LogLevel.All);
options.AddArgument("--verbose");
return new ChromeDriver(service, options);
}
It doesn't work though. Is there any other way to perform it?

How to use AndroidDriver or IOSDriver without DesiredCapabilities(which is deprecated)?

AndroidDriver and IOSDriver require to have DesiredCapabilities as input.
Now, as this is deprecated how can I use these drivers?
My code example:
DesiredCapabilities cap = new DesiredCapabilities();
cap.SetCapability("deviceName", ConfigReader("DeviceID"));
cap.SetCapability("udid", ConfigReader("DeviceID"));
cap.SetCapability("platformName", "Android");
cap.SetCapability("systemPort", "SystemPort");
cap.SetCapability("language", ConfigReader("Language"));
cap.SetCapability("locale", ConfigReader("Language"));
IWebDriver driver = new AndroidDriver<AppiumWebElement>(new Uri(uri), cap);
Can I get real example of alternative to this considering DesiredCapabilities deprecation?
There is also a similar topic for android still without proper answer DesiredCapabilities for Selenium native android application obsolete
We can create a session by using AddAdditionalCapability http://appium.io/docs/en/commands/session/create/
AppiumOptions capabilities = new AppiumOptions();
appiumOptions.AddAdditionalCapability(MobileCapabilityType.PlatformName, "Android");
appiumOptions.AddAdditionalCapability(MobileCapabilityType.PlatformVersion, "7.1.1");
appiumOptions.AddAdditionalCapability(MobileCapabilityType.DeviceName, "Android Device");
appiumOptions.AddAdditionalCapability("appPackage", "com.instagram.android");
appiumOptions.AddAdditionalCapability("appActivity", "com.instagram.android.activity.MainTabActivity");
AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new Uri("http://127.0.0.1:4723/wd/hub"), appiumOptions);

Selenium Why setting acceptuntrustedcertificates to true for firefox driver doesn't work?

I'm developping some selenium tests and I face an important issue because I didn't found a "real" solution when I test my site with secure connection (HTTPS). All solutions I found on stackoverflow are out of date or doesn't work:
I am writing a Selenium script in Firefox but I am getting "Untrusted Certificate"
How to disable Firefox's untrusted connection warning using Selenium?
Handling UntrustedSSLcertificates using WebDriver
The only workaround I have is to use the nightly mozilla release as indicated on github: https://github.com/mozilla/geckodriver/issues/420
private IWebDriver driver;
private string baseURL;
private FirefoxOptions ffOptions;
private IWait<IWebDriver> wait;
[SetUp]
public void SetupTest()
{
ffOptions = new FirefoxOptions();
ffOptions.BrowserExecutableLocation = #"D:\AppData\Local\Nightly\firefox.exe";
FirefoxProfile profile = new FirefoxProfile();
profile.AssumeUntrustedCertificateIssuer = false;
profile.AcceptUntrustedCertificates = true;
ffOptions.Profile = profile;
ffOptions.LogLevel = FirefoxDriverLogLevel.Info;
driver = new FirefoxDriver(FirefoxDriverService.CreateDefaultService(), ffOptions, TimeSpan.FromSeconds(30));
//[...]
}
Configuration:
Firefox v47.0.1, v49.0.2, v51.0.1, v52.0b9 (i tried these differents versions)
geckodriver 0.14
selenium 3.1.0
Does anyone have a solution to avoid using nightly release ?
For information I have access only to stackoverflow and github due to my internet policy, and please don't suggest me to use chrome!
Thank for your help!
Yeah, it's a bug on the geckodriver. You can find it here!
Setting the AcceptInsecureCertificates property to true in the FirefoxOptions fixed this problem for me. Here's what my initialization looked like after this change:
var profile = new FirefoxProfile();
profile.DeleteAfterUse = true;
profile.SetPreference("network.automatic-ntlm-auth.trusted-uris", LocalURL);
profile.SetPreference("network.automatic-ntlm-auth.allow-non-fqdn", true);
profile.SetPreference("webdriver_accept_untrusted_certs", true);
// Only setting this property to true did not work for me either
profile.AcceptUntrustedCertificates = true;
profile.AssumeUntrustedCertificateIssuer = false;
return new FirefoxDriver(new FirefoxOptions
{
Profile = profile,
// When I also added this line, it DID work
AcceptInsecureCertificates = true
});

How to execute Selenium Chrome WebDriver in silent mode?

When using Chrome Selenium WebDriver, it will output diagnostic output when the servers are started:
Started ChromeDriver (v2.0) on port 9515
I do not want to see these messages, how can I suppress them?
I do this
ChromeOptions options = new ChromeOptions();
options.AddArgument("--silent");
IWebDriver Driver = new ChromeDriver(options);
But diagnostic output is not suppress.
I simply do this
ChromeOptions options = new ChromeOptions();
options.AddArgument("--log-level=3");
IWebDriver driver = new ChromeDriver(options);
Good question, however, I don't know where you got that .AddArgument("--silent"); thing, as that's Chrome's command line switch, not for ChromeDriver. Also, there isn't a Chrome switch called --silent anyway.
Under OpenQA.Selenium.Chrome namespace, there is class called ChromeDriverService which has a property SuppressInitialDiagnosticInformation defaults to false. Basically what you might want to do is to create
ChromeDriverService and pass it into ChromeDriver's constructor. Please refer to the documentation here.
Here is the C# code that suppresses ChromeDriver's diagnostics outputs.
ChromeOptions options = new ChromeOptions();
ChromeDriverService service = ChromeDriverService.CreateDefaultService();
service.SuppressInitialDiagnosticInformation = true;
IWebDriver driver = new ChromeDriver(service, options);
EDIT:
ChromeDriver (not Chrome) has a command line argument --silent, which is supposed to work. SuppressInitialDiagnosticInformation in .NET binding does exactly that. However, it seems only suppress some of the messages.
Here is a closed chromedriver ticket:
Issue 116: How to disable the diagnostic messages and log file from Chrome Driver?
For me no one of previous answers did not help , my solution was:
ChromeDriverService service = ChromeDriverService.CreateDefaultService(driverLocation);
service.SuppressInitialDiagnosticInformation = true;
service.HideCommandPromptWindow = true;
var driver = new ChromeDriver(service, options);
For me the only thing that worked for
selenium-chrome-driver-2.48.2.jar
chromedriver 2.20
selenium-java-2.48.2.jar
was
ChromeOptions options = new ChromeOptions();
System.setProperty("webdriver.chrome.args", "--disable-logging");
System.setProperty("webdriver.chrome.silentOutput", "true");
driver = new ChromeDriver(options);
try this code it will hide browser with "headless" Argument but Chrome ver should > 58
( and even you can hide command prompt window )
IWebDriver driver;
ChromeOptions options = new ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArgument("test-type");
options.AddArgument("--ignore-certificate-errors");
options.AddArgument("no-sandbox");
options.AddArgument("--headless");//hide browser
ChromeDriverService service = ChromeDriverService.CreateDefaultService(#"chromedriverExepath\");
service.SuppressInitialDiagnosticInformation = true;
//service.HideCommandPromptWindow = true;//even we can hide command prompt window (with un comment this line)
options.BinaryLocation = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
driver = new ChromeDriver(service, options);
driver.Manage().Window.Maximize();
driver.Navigate().GoToUrl("https://www.example.com");
For anyone finding themselves here wanting a Java solution, there is a thread here:
Selenium chromedriver disable logging or redirect it java
To run Chrome browser with Selenium in console in completely silent mode, you should use this snippet:
options = Options()
options.headless = True
options.add_experimental_option("excludeSwitches", ["enable-logging"])
That trick will suppress any console message from either the Selenium driver or the browser itself, including the first message DevTools listening on ws://127.0.0.1 at the very start.
only add below line
System.setProperty("webdriver.chrome.silentOutput", "true");
output:-
ChromeDriver was started successfully.
Jun 28, 2022 10:38:55 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: W3C
This code works fine for me:
public static IWebDriver Driver { set; get; }
-----
Driver = CreateBrowserDriver();
////////////// Create Driver
private static IWebDriver CreateBrowserDriver()
{
try
{
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
options.AddArguments("--disable-extensions");
options.AddArgument("--headless"); // HIDE Chrome Browser
var service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
service.HideCommandPromptWindow = true; // HIDE Chrome Driver
service.SuppressInitialDiagnosticInformation = true;
return new OpenQA.Selenium.Chrome.ChromeDriver(service, options);
}
catch
{
throw new Exception("Please install Google Chrome.");
}
}
////////////// Exit Driver
public static void ExitDriver()
{
if (Driver != null)
{
Driver.Quit();
}
Driver = null;
try
{
// Chrome
System.Diagnostics.Process.GetProcessesByName("chromedriver").ToList().ForEach(px => px.Kill());
}
catch { }
}

Using a specific Firefox profile in Selenium WebDriver in C#

I am trying to use a profile I already have set up for firefox with selenium 2 but there is no documentation for C#. The code I have attempted is as follows:
FirefoxProfileManager profileManager = new FirefoxProfileManager();
FirefoxProfile profile = profileManager.GetProfile(profileName);
driver = new FirefoxDriver(profile);
Code that I have seen that is comparible in Java uses ProfilesIni instead of FirefoxProfileManager, but that is not available in C#. When setting up the driver in this way the selenium profile used has all the default settings instead of the settings specified in the profile I am trying to point to.
I am not sure that I am using the correct methods to retrieve the profile, but if anyone has used Selenium 2 with C#, any information would be helpful.
We use such method to load default firefox profile (you can create custom profile and load it):
private IWebDriver driver;
string pathToCurrentUserProfiles = Environment.ExpandEnvironmentVariables("%APPDATA%") + #"\Mozilla\Firefox\Profiles"; // Path to profile
string[] pathsToProfiles = Directory.GetDirectories(pathToCurrentUserProfiles, "*.default", SearchOption.TopDirectoryOnly);
if (pathsToProfiles.Length != 0)
{
FirefoxProfile profile = new FirefoxProfile(pathsToProfiles[0]);
profile.SetPreference("browser.tabs.loadInBackground", false); // set preferences you need
driver = new FirefoxDriver(new FirefoxBinary(), profile, serverTimeout);
}
else
{
driver = new FirefoxDriver();
}
We had the same problem that the profile wouldn't load. The problem is in FirefoxProfile (line 137). It only looks for user.js and the profile from Firefox is actually prefs.js
137>> File prefsInModel = new File(model, "user.js");
Hack solution: rename prefs.js --> user.js
The following worked for me. I had to specifically set the "webdriver.firefox.profile" preference in order to get it to work.
var allProfiles = new FirefoxProfileManager();
if (!allProfiles.ExistingProfiles.Contains("SeleniumUser"))
{
throw new Exception("SeleniumUser firefox profile does not exist, please create it first.");
}
var profile = allProfiles.GetProfile("SeleniumUser");
profile.SetPreference("webdriver.firefox.profile", "SeleniumUser");
WebDriver = new FirefoxDriver(profile);
I have the same issue, it is not a duplicate.
I am using the following which works
private IWebDriver Driver;
[Setup]
public void SetupTest()
{
string path = #"C:\Users\username\AppData\Local\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);
}
After using the aforementioned answers I had no result, so I tried the following alternate way:
First, create the desired profile by typing about:profiles on Firefox address bar.
Second, the C# code. Note that the profile name we created on first step is passed as an argument.
public IWebDriver driver { get; set; }
public Selenium(String nombrePefil)
{
if (this.driver == null)
{
FirefoxOptions options = new FirefoxOptions();
options.AddArgument("--profile " + nombrePefil);
this.driver = new FirefoxDriver(options);
}
}
I also encountered the same issue, and after searching and trying many different combinations I was able to get Selenium to load a specific profile when using the RemoteWebDriver.
Grid configuration
I launch the HUB using a batch file containing the following
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar C:\Downloads\Selenium\selenium-server-standalone-2.20.0.jar -role hub -maxSession 50 -Dwebdriver.firefox.profile=Selenium
I launch one or more nodes using a batch file containing the following (each node has a unique port number):
"C:\Program Files (x86)\Java\jre6\bin\java.exe" -jar selenium-server-standalone-2.20.0.jar -role node -hub http://127.0.0.1:4444/grid/register -browser browserName=firefox,platform=WINDOWS,version=11.0,maxInstances=2 -maxSession 2 -port 5555 -Dwebdriver.firefox.profile=Selenium
The key here is the last part of those commands, which needs to match the name of the custom profile you have created.
Code to create WebDriver instance
private readonly Uri _remoteWebDriverDefaultUri = new Uri("http://localhost:4444/wd/hub/");
private IWebDriver CreateFireFoxWebDriver(Uri remoteWebDriverUri)
{
var desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.SetCapability(CapabilityType.BrowserName, "firefox");
desiredCapabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
desiredCapabilities.SetCapability(CapabilityType.Version, "11.0");
var drv = new RemoteWebDriver(remoteWebDriverUri ?? _remoteWebDriverDefaultUri, desiredCapabilities);
return drv;
}
NOTE: The capabilities need to match those of the nodes you are running in the grid.
You can then call this method passing in the Uri of the hub, or null to default to localhost.
Seems fine with the Roaming profile rather than the local profile.
string path = #"C:\Users\username\AppData\Roaming\Mozilla\Firefox\Profiles\myi5go1k.default";
FirefoxProfile ffprofile = new FirefoxProfile(path);
Driver = new FirefoxDriver(ffprofile);

Categories

Resources