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);
Related
I am getting this error when try to run chrome with a different user. I cant seem to figure out why i am getting the error
the assembly directory and chromedriver.exe seems to be correct but chrome browser wont launch for some reason
Nuget package Selenium.Webdriver.ChromeDriver = 81.0.4044.13800
Chrome = Version 81.0.4044.138 (Official Build) (64-bit)
private static RemoteWebDriver OpenChromeBrowser(string userName)
{
Console.WriteLine("Entering Chromesetup");
var driverPath = CommonHelper.AssemblyDirectory;
Console.WriteLine($"Assembly Directory : {driverPath}");
var service = ChromeDriverService.CreateDefaultService(driverPath); //Error seems to happen here
Here is what my full call looks like for the most part for chrome. You should not be calling chromedriver.exe in your call. Just use the directory for the location of the file.
ChromeDriverService service = ChromeDriverService.CreateDefaultService(Path.Combine(GetBasePath, #"bin\Debug\"));
ChromeOptions options = new ChromeOptions();
options.AddArguments("--incognito");
driver = new ChromeDriver(service, options);
driver.Manage().Cookies.DeleteAllCookies();
public static string GetBasePath
{
get
{
var basePath =
System.IO.Path.GetDirectoryName((System.Reflection.Assembly.GetExecutingAssembly().Location));
basePath = basePath.Substring(0, basePath.Length - 10);
return basePath;
}
}
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 using a chrome Webdriver to take a screenshot on a page, if I use the "headless" argument I get this error:
[1127/115120.051:INFO:CONSOLE(157)] "Deprecation warning: moment
construction falls back to js Date.
This is discouraged and will be removed in upcoming major release.
Please refer to https://github.com/moment/moment/issues/1407 for more info.
at Function.createFromInputFallback (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:157:187)
at ie (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:157:664)
at De (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1390)
at Me (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1287)
at Se (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1007)
at Ne (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1703)
at Oe (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:158:1737)
at t (https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js:154:2701)
at e (https://s-new.tradingview.com/static/bundles/blackfriday-dialog.dba1b059b906a510ba6c.js:1:580)
at i.<anonymous> (https://s-new.tradingview.com/static/bundles/blackfriday-dialog.dba1b059b906a510ba6c.js:1:2029)", source: https://s-new.tradingview.com/static/bundles/vendors.555f7dba06d6ca8b7950.4b2fc7ae22fe.js (157)
I'm not sure if the error and the info message are related.
The same thing happens using phantomJS, but works fine if the chrome window is shown, although that's not an option since every time the screenshot gets taken, chrome steals focus.
here's what I'm trying:
static void Main()
{
ChromeOptions options = new ChromeOptions();
options.AddArgument("--disable-notifications");
options.AddArguments("--disable-gpu");
options.AddArgument("--headless");
var driver = new ChromeDriver(options);
driver.Url = "https://uk.tradingview.com/chart/?symbol=FX:GBPUSD";
var webElement = driver.FindElementByClassName("chart-widget");
string fileName = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".jpg";
Byte[] byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
System.Drawing.Bitmap screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray));
}
the error happens as the address is being passed to the driver.Url.
Any idea how to fix it or work around it?
Here is my selemium test:
[Test]
public void RunStepsTest()
{
using (var driver = new InternetExplorerDriver())
{
driver.Navigate().GoToUrl(Url);
ExecuteStep(driver, "start");
ExecuteStep(driver, "step1");
ExecuteStep(driver, "step2");
ExecuteStep(driver, "finish");
}
}
private void ExecuteStep(InternetExplorerDriver driver, string stepName)
{
var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(x => ExpectedConditions.ElementIsVisible(By.Id(stepName)));
var scrrenshot = driver.GetScreenshot();
scrrenshot.SaveAsFile(Path.Combine(ScreenshotDirectory, stepName + ".jpg"), ScreenshotImageFormat.Jpeg);
var link = driver.FindElement(By.Id(stepName));
link.SendKeys(Keys.Enter);
}
Most of time this test fails on line
scrrenshot.SaveAsFile(Path.Combine(ScreenshotDirectory, stepName + ".jpg"), ScreenshotImageFormat.Jpeg);
with message "Paramter is not valid". What do I do wrong?
In Internet Explorer driver, it's intended to throw this error .
From Github bug tracking :
Because of the limitations of how the IE driver is forced to work in
order to take full-DOM screenshots, screenshots are only supported for
browser windows viewing HTML documents. This is entirely as intended
by the driver (regardless of the behavior of Chrome or Firefox). The
driver is forced by the constraints of the IE browser itself.
Accordingly, I'm closing this as "working as intended".
If you are allowed to use other driver, you can try Firefox or Chrome Driver to have screenshot.
Try this code like this:
Screenshot ss = ((ITakesScreenshot)driver).GetScreenshot();
ss.SaveAsFile("e:\\pande", System.Drawing.Imaging.ImageFormat.Jpeg);
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);