如何使用C#应用程序以编程方式控制Firefox?

6

我想编写一个程序,可以打开火狐浏览器的默认实例,其中包含我的不同登录信息,并在几个网站之间切换。我已经使用以下代码基本实现了这个功能:

System.Diagnostics.Process.Start("firefox.exe", "thisIsMyURL");

然而,如你所知,这只是打开一个新的Firefox进程,并将给定的URL作为默认网站打开。为了实现我的目标,我基本上需要打开一个新的Firefox进程,在页面上完成所需操作,终止该进程,然后针对每个需要的页面重复此过程。这不是理想的解决方案。因此,我希望有人能够通过API或库等编程方式控制Firefox。我在Google上搜索过,到目前为止只找到了过时的解决方案,根本没有解决我的问题。
感谢您的帮助!非常感激您所提供的一切。

3
一个可能的搜索词是“硒”。不确定是否可以添加更多的信息来完整回答 :)... - Alexei Levenkov
谢谢!这看起来是我要走的路。我得试一下,然后告诉你。 - Sean Cogan
3个回答

4

你可以使用 Selenium WebDriver 进行 C# 编程。

Selenium WebDriver 是一个跨平台的 API,它允许你使用 Java、C# 等语言的 API 来控制各种浏览器。

以下是使用 Selenium WebDriver 编写 C# 测试代码的示例。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using OpenQA.Selenium.Interactions;
using OpenQA.Selenium.Interactions.Internal;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.IE;
using NUnit.Framework;
using System.Text.RegularExpressions;

namespace sae_test
{   class Program
    {   private static string baseURL;
        private static StringBuilder verificationErrors;

        static void Main(string[] args)
        {   // test with firefox
            IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
            // test with IE
            //InternetExplorerOptions options = new InternetExplorerOptions();
            //options.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
            //IWebDriver driver = new OpenQA.Selenium.IE.InternetExplorerDriver(options);
            SetupTest();
            driver.Navigate().GoToUrl(baseURL + "Account/Login.aspx");
            IWebElement inputTextUser = driver.FindElement(By.Id("MainContent_LoginUser_UserName"));
            inputTextUser.Clear();
            driver.FindElement(By.Id("MainContent_LoginUser_UserName")).Clear();
            driver.FindElement(By.Id("MainContent_LoginUser_UserName")).SendKeys("usuario");
            driver.FindElement(By.Id("MainContent_LoginUser_Password")).Clear();
            driver.FindElement(By.Id("MainContent_LoginUser_Password")).SendKeys("123");
            driver.FindElement(By.Id("MainContent_LoginUser_LoginButton")).Click();
            driver.Navigate().GoToUrl(baseURL + "finanzas/consulta.aspx");
            // view combo element
            IWebElement comboBoxSistema = driver.FindElement(By.Id("MainContent_rcbSistema_Arrow"));
            //Then click when menu option is visible 
            comboBoxSistema.Click();
            System.Threading.Thread.Sleep(500);
            // container of elements systems combo
            IWebElement listaDesplegableComboSistemas = driver.FindElement(By.Id("MainContent_rcbSistema_DropDown"));
            listaDesplegableComboSistemas.FindElement(By.XPath("//li[text()='BOMBEO MECANICO']")).Click();
            System.Threading.Thread.Sleep(500);
            IWebElement comboBoxEquipo = driver.FindElement(By.Id("MainContent_rcbEquipo_Arrow"));
            //Then click when menu option is visible 
            comboBoxEquipo.Click();
            System.Threading.Thread.Sleep(500);
            // container of elements equipment combo
            IWebElement listaDesplegableComboEquipos = driver.FindElement(By.Id("MainContent_rcbEquipo_DropDown"));

            listaDesplegableComboEquipos.FindElement(By.XPath("//li[text()='MINI-V']")).Click();
            System.Threading.Thread.Sleep(500);

            driver.FindElement(By.Id("MainContent_Button1")).Click();            
            try
            {   Assert.AreEqual("BOMBEO MECANICO_22", driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_LabelSistema\"]")).Text);
            }
            catch (AssertionException e)
            {   verificationErrors.Append(e.Message);
            }
            // verify coin format $1,234,567.89 usd
            try
            {   Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelInversionInicial\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
            }
            catch (AssertionException e)
            {   verificationErrors.Append(e.Message);
            }
            try
            {   Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoOpMantto\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
            }
            catch (AssertionException e)
            {   verificationErrors.Append(e.Message);
            }
            try
            {   Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelCostoEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
            }
            catch (AssertionException e)
            {   verificationErrors.Append(e.Message);
            }
            try
            {   Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelcostoUnitarioEnergia\"]")).Text, "\\$((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})? usd"));
            }
            catch (AssertionException e)
            {   verificationErrors.Append(e.Message);
            }
            // verify number format 1,234,567.89
            try
            {   Assert.IsTrue(Regex.IsMatch(driver.FindElement(By.XPath("//*[@id=\"MainContent_RejillaRegistroFinanciero_ctl00_ctl04_labelConsumo\"]")).Text, "((,)*[0-9]*[0-9]*[0-9]+)+(\\.[0-9]{2})?"));
            }
            catch (AssertionException e)
            {   verificationErrors.Append(e.Message);
            }
            System.Console.WriteLine("errores: " + verificationErrors);
            System.Threading.Thread.Sleep(20000);
            driver.Quit();
        }

        public static void SetupTest()
        {   baseURL = "http://127.0.0.1:8081/ver.rel.1.2/";
            verificationErrors = new StringBuilder();
        }

        protected static void mouseOver(IWebDriver driver, IWebElement element)
        {   Actions builder = new Actions(driver);
            builder.MoveToElement(element);
            builder.Perform();
        }

        public static void highlightElement(IWebDriver driver, IWebElement element)
        {   for (int i = 0; i < 2; i++)
            {   IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
                js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
                        element, "color: yellow; border: 2px solid yellow;");
                js.ExecuteScript("arguments[0].setAttribute('style', arguments[1]);",
                        element, "");
            }
        }
    }
}

请在http://vidadigital.com.mx/publicacion/source/Program.cs下载。


这看起来是一个很好的开始,谢谢Victor!我会试一下并告诉你结果。 - Sean Cogan
好的,这绝对是一个不错的开始。有没有办法让Selenium使用与我的默认Firefox设置相同的扩展? - Sean Cogan

3
我一段时间前在阅读MSDN杂志,看到了一篇关于一个名为“Watir”的项目的文章,这引起了我的兴趣,因为当时我正在进行大量的自动化测试。我进一步了解后发现实际上有一个名为WatiN 的基于.NET的项目。你可以查看一下,我认为它正是你想要做的。

http://watin.org/

http://watir.com/


0

首先使用以下命令启动进程:

Process.Start("firefox.exe", "www.example.com");

然后要杀死它,你需要执行以下操作:

Process[] processes = Process.GetProcessesByName("firefox.exe");
foreach (Process p in processes)
{
    if (p.ProcessName.Equals("firefox.exe", StringComparison.OrdinalIgnoreCase))
    {
        p.Kill();
    }
}

他并不是在问那个,他在问如何自动化一个实例,而不是创建和销毁每一个实例。 - Mark Hall
我还没有见过这样的东西,我分享了我所知道的。也许如果有人能在这里发布代码,那肯定会帮助我们所有人:/ - Atif Imtiaz
你可以通过这个链接查看我找到的一个类似的问题:https://dev59.com/2EzSa4cB1Zd3GeqPmWhS?rq=1 - Atif Imtiaz
3
很遗憾,Atif,这个解决方案恰恰是我想要避免的。不过还是谢谢你的帮助。 - Sean Cogan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接