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);
Related
How can I set chrome driver path whilst having chrome.options. At the moment I am creating options to remove mic/camera permissions in chrome but I am having to feed the options path into the driver.
Here is my code at the moment for an idea. The chrome driver is starting up and working fine with the chrome.options setting being applied but I'd like to know a way to feed the variables chromeDriverPath and options when creating the new driver
I am new with selenium so please no judgement :)
IWebDriver driver;
string chromeDriverPath;
void SetChromeDriverPath()
{
OperatingSystem os = Environment.OSVersion;
string osName = os.Platform.ToString().ToLower();
if (osName == "win32nt")
chromeDriverPath = Environment.CurrentDirectory.ToString() + "\\tools\\selenium\\chrome\\windows\\";
if (osName == "unix")
chromeDriverPath = Environment.CurrentDirectory.ToString() + "\\tools\\selenium\\chrome\\linux\\";
if (osName == "macosx")
chromeDriverPath = Environment.CurrentDirectory.ToString() + "\\tools\\selenium\\chrome\\mac\\";
}
public IWebDriver GetChromeDriver()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("use-fake-ui-for-media-stream");
options.AddArgument("--start-maximized");
SetChromeDriverPath();
driver = new ChromeDriver(options);
return driver;
}
https://www.selenium.dev/selenium/docs/api/dotnet/html/T_OpenQA_Selenium_Chrome_ChromeDriver.htm
you can see that the chromedriver path is expected as an argument to chromedriver so you can use:
driver = new ChromeDriver(chromeDriverPath ,options);
I'm learning how to write selenium tests in C# and am getting this error when trying to run the test case below. It is failing on: IWebElement query = driver.FindElement(By.Name("q"));
Test method SeleniumDemo.SearchGoogle.SearchForCheese threw exception:
System.ArgumentException: elementDictionary (Parameter 'The specified dictionary does not contain an element reference')
Code:
[TestMethod]
public void SearchForCheese()
{
using (var driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)))
{
driver.Navigate().GoToUrl("http://www.google.com");
// Find text input
IWebElement query = driver.FindElement(By.Name("q"));
// Enter something to search for
query.SendKeys("cheese");
// Submit form
query.Submit();
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(d => d.Title.Contains("cheese"));
Assert.AreEqual(driver.Title, "cheese - Google Search");
};
}
Any ideas? Thank you in advance!
Check and make sure your ChromeDriver() version matches what is on your local machine.
Below is an XUnit test that will re-create your issue using the WebDriverManager NuGet package where you can manually specify which version of webdriver you want downloaded if it's not available on your machine:
[Fact]
public void ChromeDriverThrows_ArgumentException_True()
{
var google = "https://www.google.com/";
var message = "elementDictionary (Parameter 'The specified
dictionary does not contain an element
reference')";
// Specify a different of ChromeDriver than what is installed on machine.
_ = new DriverManager().SetUpDriver(
"https://chromedriver.storage.googleapis.com/2.25/chromedriver_win32.zip",
Path.Combine(Directory.GetCurrentDirectory(), "chromedriver.exe"),
"chromedriver.exe"
);
var driver = new ChromeDriver();
driver.Navigate().GoToUrl(google);
var exception = Assert.Throws<ArgumentException>(() => driver.FindElement(By.Name("q")));
Assert.True(message == exception.Message, $"{exception.Message}");
}
If you choose to use WebDriverManager in your project, you can use automatically set the below to automatically download a chromedriver.exe matching the version of Chrome installed in your machine so you don't have to manually manage them:
new DriverManager().SetUpDriver(new ChromeConfig(), VersionResolveStrategy.MatchingBrowser);
I'm trying to launch a specific URL using Firefox. But I'm only able to open Firefox browser and not able to launch that URL.
class BrowserHelper
{
IWebDriver driver;
string path = Path.Combine(Environment.CurrentDirectory, #"gecko\\");
public void Navigate(string url)
{
path = path.Replace(#"\", #"\\");
var driverService = FirefoxDriverService.CreateDefaultService(path);
driverService.HideCommandPromptWindow = true;
if (driver == null)
{
driver = new FirefoxDriver(driverService);
}
driver.Url = url;
driver.Navigate().GoToUrl(driver.Url);
driver.Manage().Window.Maximize();
}
}
class Realtest
{
BrowserHelper BH = new BrowserHelper();
public void test()
{
string search ="apple";
BH.Navigate("https://www.google.com/search?q=" + search);
}
}
And I can only get this page:
Here's the final URL I want to launch: https://www.google.com.sg/search?q=apple
Any suggestions? Thanks in advance.
I have tried the below code (in Java), and it's working fine by launching the browser and loading the URL also.
System.setProperty("webdriver.gecko.driver","Drivers/geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://www.google.com.sg/search?q=apple");
So I feel the problem is with geckodriver version and FireFox browser installed in your local machine. I would suggest you update FireFox and geckodriver to the latest version.
There is also a pretty easy solution using the command line with c#.
Simply execute the following command to open a new Firefox Tab with the given URL:
start firefox wikipedia.de
You can also start a new Firefox instance if you wish:
start firefox -new-instance wikipedia.de
Last but not least the .Net Code to execute the commands in CLI:
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
{
Arguments = "/c start firefox wikipedia.de",
CreateNoWindow = true,
FileName = "CMD.exe"
});
There is also a lot of other stuff that can be done with Firefox commandLine paramters. You an find all of them here:
https://developer.mozilla.org/en-US/docs/Mozilla/Command_Line_Options?redirectlocale=en-US&redirectslug=Command_Line_Options
This also works with chrome and opera, simply call
start opera wikipedia.de
instead of firefox.
You do not need to set driver.Url, remove that line.
driver.Navigate().GoToUrl(url);
driver.Manage().Window.Maximize();
Also, if you simply want to launch a single URL without interacting with the page, then Selenium is overkill.
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
});
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));
}