简体   繁体   中英

How to launch a specific URL with Firefox in C#

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM