Подтвердить что ты не робот

Как вы можете автоматизировать Firefox из приложения С#?

Начните с простейшей задачи по захвату URL-адреса в Firefox из приложения С#. Он появляется с помощью user32.dll. Функции Windows API не будут работать так же, как подход к захвату URL-адреса в IE.

4b9b3361

Ответ 1

Если мне нужно сделать захват URL с помощью AutoHotkey, например, я бы послал Ctrl + L (поместил фокус в адресную строку и выделил контент) и Ctrl + C (выбор копии в буфер обмена). Затем вы просто читаете буфер обмена, чтобы получить информацию.

Для более сложных задач я бы использовал расширения Greasemonkey или iMacros, возможно, вызванные схожими сочетаниями клавиш.

Ответ 2

WatiN поддерживает Firefox.

Ответ 3

WebAii может автоматизировать FireFox, включая настройку и получение URL-адреса

Ответ 4

Похоже, что он очень бета-ey, но кто-то построил .NET connector для mozrepl. Фактически, кодовая база mozrepl просто перемещалась в github. Но mozrepl позволяет отправлять команды в среду XUL.

Ответ 5

Попробуйте Selenium (механизм тестирования Google - http://seleniumhq.org/) Вы можете записать задачу (связанный с интерфейсом веб-страниц), сделанный в Firefox, и конвертировать запись в источник С#:)

Ответ 6

Один инструмент Microsoft, с которым я столкнулся:

Автоматизация пользовательского интерфейса, как часть .NET 3.5 http://msdn.microsoft.com/en-us/library/aa348551.aspx

Вот пример: http://msdn.microsoft.com/en-us/library/ms771286.aspx

У меня нет UI Spy на моем компьютере для опроса Firefox, поэтому я не знаю, поможет ли это с вашей проблемой user32.dll.

Ответ 7

Вы можете использовать Selenium WebDriver для С#.

Это межплатформенный API, который позволяет вам управлять различными браузерами с использованием API для Java, С# и других.

Прикрепление кода С# с тестами Selenium WebDriver.

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, "");
        }
    }
}
}