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.
Related
I know there is a way in Selenium to launch a browser (at least in Chrome) and later attach to that instance. Can you do the same thing through Atata?
Here is the sample that starts Chrome and then attaches Atata (ChromeDriver instance) to the created Chrome.
// Set static or find available port number:
int chromePort = 9222;
// Run Chrome process:
Process chromeProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = #"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
Arguments = $"https://demo.atata.io/ --new-window --remote-debugging-port={chromePort} --user-data-dir=C:\\Temp"
}
};
chromeProcess.Start();
// Create Atata context attached to the Chrome:
AtataContext.Configure()
.UseChrome()
.WithOptions(x => x.DebuggerAddress = $"127.0.0.1:{chromePort}")
.Build();
// Do some actions using Atata:
Go.To<OrdinaryPage>(url: "https://demo.atata.io/products")
.PageTitle.Should.Contain("Products");
// Clean up (just don't do it exactly like here. Use "using (...)", etc.):
AtataContext.Current.Dispose();
chromeProcess.CloseMainWindow();
chromeProcess.Dispose();
The main thing to attach to Chrome is .UseChrome().WithOptions(x => x.DebuggerAddress = $"127.0.0.1:{chromePort}").
The problem is that I need to get the PID of IE browser instances so that I can close the IE browser(Working in C#).
I launched the IE browser using Selenium and then used Driver Service class as :-
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService();
Console.WriteLine(driverdetails.Port);
The plan is to get the port and then have its child process. I am able to do so using a debugger by entering the value of Port manually. But, the port fetched by driverdetails.Port was not the actual port used by my driver.
Is there any was, I can find the Port for any given driver service?
For IE i have an alternative to launch IE and get the URL with port which says http://localhost:. However, this is not the case with other browsers. My want is to make the generic code and hence I am using the Driver Service object.
As far as I know, the InternetExplorerDriverService's ProcessID property gets the process ID of the running driver service executable, and we can't get the IE browser instance PID through the InternetExplorer webdriver. If you want to get the PID, you could try to use the Process class.
From your description, it seems that you want to close the IE tab or window by using the IE Webdriver. If that is the case, I suggest you could use InternetExplorerDriver WindowHandles to get the opened windows, then use the switchto method to switch the window and check the url or title, finally, call the Close method to close the IE window. Please refer to the following sample code:
private const string URL = #"https://dillion132.github.io/login.html";
private const string IE_DRIVER_PATH = #"D:\Downloads\webdriver\IEDriverServer_x64_3.14.0"; // where the Selenium IE webdriver EXE is.
static void Main(string[] args)
{
InternetExplorerOptions opts2 = new InternetExplorerOptions() { InitialBrowserUrl = "https://www.bing.com", IntroduceInstabilityByIgnoringProtectedModeSettings = true, IgnoreZoomLevel = true };
using (var driver = new InternetExplorerDriver(IE_DRIVER_PATH, opts2))
{
driver.Navigate();
Thread.Sleep(5000);
//execute javascript script
var element = driver.FindElementById("sb_form_q");
var script = "document.getElementById('sb_form_q').value = 'webdriver'; console.log('webdriver')";
IJavaScriptExecutor jse = (IJavaScriptExecutor)driver;
jse.ExecuteScript(script, element);
InternetExplorerDriverService driverdetails = InternetExplorerDriverService.CreateDefaultService(IE_DRIVER_PATH);
Console.WriteLine(driverdetails.Port);
// open multiple IE windows using webdriver.
string url = "https://www.google.com/";
string javaScript = "window.open('" + url + "','_blank');";
IJavaScriptExecutor jsExecutor = (IJavaScriptExecutor)driver;
jsExecutor.ExecuteScript(javaScript);
Thread.Sleep(5000);
//get all opened windows (by using IE Webdriver )
var windowlist = driver.WindowHandles;
Console.WriteLine(windowlist.Count);
//loop through the list and switchto the window, and then check the url
if(windowlist.Count > 1)
{
foreach (var item in windowlist)
{
driver.SwitchTo().Window(item);
Console.WriteLine(driver.Url);
if(driver.Url.Contains("https://www.bing.com"))
{
driver.Close(); //use the Close method to close the window. The Quit method will close the browser window and dispose the webdriver.
}
}
}
Console.ReadKey();
}
Console.ReadKey();
}
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);
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 { }
}
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);