Using Custom Firefox Binary Location with Headless Firefox Options - c#

I am attempting to write C# code that will launch Mozilla Firefox, browse to a website and automate form entry. I can get this to function correctly without being headless, but now I am looking to convert my code to run a headless Firefox Browser.
The following code will function if the latest version of Selenium and Firefox driver is installed via NuGet and also the latest version of the geckodriver is at the appropriate folder location.
What needs to be done to make this code open a headless Mozilla Firefox?
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
namespace GoogleSearch
{
class LaunchFirefox
{
static void Main(string[] args)
{
//Start Firefox Gecko Driver Service from Custom Location
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"C:\GoogleSearch");
//Force the CMD prompt window to automatically close and suppress diagnostic information
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
//Launch Mozilla Firefox from custom location
service.FirefoxBinaryPath = #"C:\Firefox\firefox.exe";
//Initialize new Firefox Driver with the above service arguments
FirefoxDriver driver = new FirefoxDriver(service);
//Navigate to the Google website
driver.Navigate().GoToUrl("https://www.google.com");
//Automate custom Google Search Submission
driver.FindElement(By.Name("q")).SendKeys("Stack Overflow");
}
}
}
I tried inserting Firefox options, but that option doesn't seem to be available.
I get the following error when I attempt adding options to the firefox driver initialization line:
Error CS1503 Argument 2: cannot convert from 'OpenQA.Selenium.Firefox.FirefoxOptions' to 'OpenQA.Selenium.Firefox.FirefoxProfile'
Any assistance would be appreciated.
I am running the following software:
Windows 7
Visual Studio Community Edition 2017
Mozilla Firefox 61.0.1
Gecko Driver 0.21.0

Since using Firefox in headless mode is accomplished by passing a --headless option to the Firefox command line, the code you want is similar to the following:
// DISCLAIMER WARNING! The below code was written from
// memory, without benefit of an IDE. It may not be entirely
// correct, and may not even compile without modification.
//Start Firefox Gecko Driver Service from Custom Location
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"C:\GoogleSearch");
//Force the CMD prompt window to automatically close and suppress diagnostic information
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
//Launch Mozilla Firefox from custom location
FirefoxOptions options = new FirefoxOptions();
options.BrowserExecutableLocation = #"C:\Firefox\firefox.exe";
options.AddArgument("--headless");
//Initialize new Firefox Driver with the above service and options
FirefoxDriver driver = new FirefoxDriver(service, options);
//Navigate to the Google website
driver.Navigate().GoToUrl("https://www.google.com");
//Automate custom Google Search Submission
driver.FindElement(By.Name("q")).SendKeys("Stack Overflow”);
As long as you’re using 3.14 or later of the .NET bindings, that code, or something similar to it, should work.

I finally found the answer to this question. The stack overflow page here helped a lot in finding the answer to this question:
Setting BrowserExecutableLocation in FirefoxOptions in Selenium doesn't prevent an "Unable to find a matching set of capabilities" error
Here is my code for headless firefox that works very well when Firefox is used in a non-default location:
using System;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
namespace GoogleSearch
{
class LaunchFirefox
{
static void Main(string[] args)
{
//Start Firefox Gecko Driver Service from Custom Location
FirefoxDriverService service = FirefoxDriverService.CreateDefaultService(#"C:\FirefoxDriver");
//Force the CMD prompt window to automatically close and suppress diagnostic information
service.HideCommandPromptWindow = true;
service.SuppressInitialDiagnosticInformation = true;
//Initialize Firefox Options class
FirefoxOptions options = new FirefoxOptions();
//Set Custom Firefox Options
options.BrowserExecutableLocation = #"C:\Mozilla Firefox\Firefox.exe";
//options.AddArgument("--headless");
//Start Firefox Driver with service, options, and timespan arguments
FirefoxDriver driver = new FirefoxDriver(service, options, TimeSpan.FromMinutes(1));
//Navigate to the Google website
driver.Navigate().GoToUrl("https://www.google.com");
//Automate custom Google Search Submission
driver.FindElement(By.Name("q")).SendKeys("Stack Overflow");
}
}
}
Hope the helps someone else using C# code and trying to run headless firefox.
Blessings,
Seth

Related

Selenium webdriver - How to connect to the same firefox instance open by Visual Studio using C#

Hello friends. I would like some help.
I've been trying to use the same instance of Firefox window open by Visual Studio at first time.
The question is, how to pickup the same window browser and continue to testing without it close the browser and open again every time i want to do a testing?
I know there is a lot of questions about this topic, but some that I've found is applicable for old versions of selenium and some codes didn't work due to be deprecated.
What i can do with success:
I can work normally with traditional method to test a unit, opening Firefox at beginning and close after the end of test:
[ClassInitialize]
public static void InitializeClass(TestContext testContext) {
driver = new FirefoxDriver();
}
Then i commented the following lines to keep the window open when test is complete:
//driver.Quit();
//driver.Close();
//driver.Dispose();
What i can't manage to:
With searches I've been made, i read that we can connect to an existing session already open before. So i tried with the following:
[ClassInitialize]
public static void InitializeClass(TestContext testContext) {
FirefoxOptions options = new FirefoxOptions();
driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options);
//driver = new FirefoxDriver();
On the example above, I've commented driver = new FirefoxDriver(); and used the method FirefoxOptions instead of the deprecated DesiredCapabilities.firefox() and when i try to connect to the open firefox window, i got an error and i can't go on. On log, there's a line saying:
Was'n possible to copy the file "..\packages\Selenium.Firefox.WebDriver.0.27.0\build\driver\geckodriver.exe" to "..\bin\debug\geckodriver.exe"
The file geckodriver.exe (61484) is being used by another process
With this, i tried another different ways to reach what i expect like:
[ClassInitialize]
public static void InitializeClass(TestContext testContext) {
FirefoxOptions options = new FirefoxOptions();
driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options);
options.AddArgument("--marionette-port " + "2828" + "--connect-existing");
FirefoxDriverService ffDriverService = FirefoxDriverService.CreateDefaultService();
ffDriverService.BrowserCommunicationPort = 4444;
}
for last i tried to open a separated instance of Firefox to try to connect to like below:
firefox.exe --marionette -start-debugger-server 2828 -profile %temp%\FirefoxTEMP
I got success on open a instance of marionette,but i continuing unable to attach the test to this open window.
I appreciate your attention and forgive me for some newbie techniques i made.
Questions I've read:
How to connect Selenium to existing Firefox browser? (Python)
How to connect Selenium Webdriver to existing Firefox/Chrome browser session?
How to connect to an already open browser?
edit:
take a look on this thread to understand that it's a common request:
Allow webdriver to attach to a running browser - GitHub
You can use "detach" and change Firefox to Chrome(because I didn't see that option in Firefox). Link to link. Shortly, it keeps your browser open depending on the option "true"/"false".
ChromeOptions options = new ChromeOptions();
options.setExperimentalOption("detach", true);
You can use bad habits and simply use a global variable.
global browser

Is there a way to open HTTP web in Edge using selenium and iedriver?

So i'm using this code but if the web is HTTP it opens on IE instead of Edge.
var ieOptions = new InternetExplorerOptions();
ieOptions.EdgeExecutablePath = "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe";
IWebDriver driver = new InternetExplorerDriver(ieOptions);
driver.Url = "some http web";
is there a way to force it on edge?
You need to download Microsoft Edge Driver and use that. The name of the class your code currently uses should give you a hint about why Internet Explorer is being opened:
IWebDriver driver = new InternetExplorerDriver(ieOptions);
^^^^^^^^^^^^^^^^
It is right in the name: InternetExplorerDriver. You are using the web driver for Internet Explorer. If you want to automate Edge, you need to use EdgeDriver.
I think the curious thing is that Edge is launched when loading an HTTPS URL when using InternetExplorerDriver. I suspect there are Windows Policies installed that override Internet Explorer causing Edge to be launched instead.
Create InternetExplorerDriver and pass the InternetExplorerOptions:
var options = new InternetExplorerOptions
{
AttachToEdgeChrome = true,
EdgeExecutablePath = "C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"
};
var driver = new InternetExplorerDriver(options);
driver.Url = "https://example.com";
This will open Edge in IE mode...
If you don't need IE mode you need to use EdgeDriver instead of InternetExplorerDriver and EdgeOption instead of InternetExplorerOptions

Selenium: Chrome doesn't maximize under IIS

I have a web API application. When I call some URL, selenium starts and goes to some site and makes screenshots and saves them to files.
When I run code in Visual Studio by pressing F5, the application works well.
But after I'd publish my application to IIS, I noticed that browser doesn't maximize and I got small screenshots.
I use a chrome driver, because IE driver and Firefox driver throw error
unable to connect.
I tried this code:
var chromeOptions = new ChromeOptions()
{
};
chromeOptions.AddArgument("--start-maximized");
using (IWebDriver driver = new ChromeDriver(chromeOptions))
{
driver.Manage().Window.Maximize();
/*driver.Manage().Window.Size = new System.Drawing.Size(1920, 1040); this doesn't work too*/
I notice when selenium starts under IIS I don't see a browser window. I only see a process of chrome in the task manager.
How to make maximize window of a browser under IIS?
Instead of :
chromeOptions.AddArgument("--start-maximized");
Can you try :
chromeOptions.AddArgument("start-maximized");
And remove :
driver.Manage().Window.Maximize();

Is it possible to use ISelenium/DefaultSelenium without installing Selenium Server?

I used IWebDriver to control IE for testing before. But the methods supported for IWebDriver and IWebElement are so limited. I find that ISelenium/DefaultSelenium which belongs to Selenium namespace are very useful. How can I use them to control an IE without installing the Selenium Server??
Here's the constructor of DefaultSelenium:
ISelenium sele = new DefaultSelenium(**serveraddr**, **serverport**, browser, url2test);
sele.Start();
sele.Open();
...
Seems that I have to install Selenium Server before I create an ISelenium object.
My case is, I'm trying to build a .exe application with C#+Selenium which can run on different PCs and it's impossible to install Selenium Server on all PCs(you never know which one is the next to run the app).
Does anyone know how to use ISelenium/DefaultSelenium without installing the server?
thx!
There are some solutions in Java without using the RC Server:
1) For the selenium browser startup:
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setBrowserName("safari");
CommandExecutor executor = new SeleneseCommandExecutor(new URL("http://localhost:4444/"), new URL("http://www.google.com/"), capabilities);
WebDriver driver = new RemoteWebDriver(executor, capabilities);
2) For selenium commands:
// You may use any WebDriver implementation. Firefox is used here as an example
WebDriver driver = new FirefoxDriver();
// A "base url", used by selenium to resolve relative URLs
String baseUrl = "http://www.google.com";
// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");
// Get the underlying WebDriver implementation back. This will refer to the
// same WebDriver instance as the "driver" variable above.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();
//Finally, close the browser. Call stop on the WebDriverBackedSelenium instance
//instead of calling driver.quit(). Otherwise, the JVM will continue running after
//the browser has been closed.
selenium.stop();
Descripted here: http://seleniumhq.org/docs/03_webdriver.html
Google for something similar in C#.
Theres no other way to achieve that.

When using Selenium Webdriver, I get the following error using the InternetExplorerDriver - "Unexpected error launching Internet Explorer...."

I'm trying to instantiate an InternetExplorerDriver in C#, and every time I do I get the following error message:
System.InvalidOperationException : Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones. (NoSuchDriver)
Now I'm not sure how to sort this out, but the line of code that triggers the error in question is:
IWebDriver driver = new InternetExplorerDriver();
The documentation for InternetExplorerDriver suggests that I can pass in an ICapabilities object in an overloaded constructor, but that only has the properties BrowserName, IsJavaScriptEnabled, Platform and Version. None of these seem to suggest that they can solve the issue.
Is there something I need to do within the implementation to sort this out?
Or do I have to modify some settings within IE9 itself?
For reference, if your wish to override the security options here's the c# code:
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace SeleniumTests
{
[TestFixture]
public class Test
{
private IWebDriver driver;
[SetUp]
public void Setup()
{
var options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
driver = new InternetExplorerDriver(options);
}
}
}
Update:
My previous answer used an older version of Selenium 2.0, I've now updated the code to work against Selenium DotNet-2.21.0 and included the correct namespaces.
Internet Explorer defines four zones, each with a different security level and the ability to enable or disable Protected Mode. The error message is trying to tell you that Protected Mode must either be disabled or enabled for all zones because of a limitation in Selenium's InternetExplorerDriver.
For more details, see the defect report in Selenium's issue tracker and the screenshot of Internet Explorer security options.
This should solve the problem:
InternetExplorerOptions options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
IWebDriver driver = new InternetExplorerDriver(options);
Aleh's Answer resolved the issue for me, but I found I also needed to specify the file path for the location of the IEDriverServer. Just posting in case anyone else runs into a similar issue.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
namespace SeleniumTest
{
class Program
{
static void Main(string[] args)
{
InternetExplorerOptions options = new InternetExplorerOptions();
options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
IWebDriver driver = new InternetExplorerDriver("C:\\Selenium", options);
driver.Navigate().GoToUrl("http://www.stackoverflow.com");
}
}
}
Refer link: -
https://intensetesting.wordpress.com/2014/09/16/error-80070012-unexpected-error-launching-spoon-based-internet-explorer/
If you upgrade or degrade the native IE browser which was installed during OS installation it will not allow opening the spoon browsers. Every time we need to make the default IE browser then it will work.
Suppose while you installed the OS the default IE version is IE8 and you upgraded to IE9 for some purpose. In this case it won’t allow navigating any application in the Spoon browsers (only browser will open up) and it will simply throw the error message like “Unexpected error launching internet explorer IELaunchURL error returned 80070012”.
I found the following worked for me (none of the answers above worked)
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
desiredCapabilities.SetCapability(InternetExplorerDriver.IntroduceInstabilityByIgnoringProtectedModeSettings, true);
driver = new InternetExplorerDriver(desiredCapabilities);
I found that it worked, but I also recieved an "(Unexpected Alert Open)" when I tried to run a test, which of all things, turned out I had to disable the IE developer toolbar.
I had similar problem on a server that was built and I had no way of changing the protected mode. It was disabled by the system administrator. Even when I logged in with an admin account, I was unable to change the protected mode. However, I was able to run selenium with no problem.

Categories

Resources