public void ArticleClassificationIsVulnerabilities()
        {
            var urlList = new List<string>();
            //Fetching Parent node Urls
            urlList.AddRange(HPFortifyXMLMapping.Select(x => x.ArticleUrl));
            //Fetching Child urls
            var subcategoryUrl = (from query in HPFortifyXMLMapping
                                  from subcategory in query.SubCategories
                                  select subcategory.ArticleUrl).ToList();

            //Merging both Url list to make processing easier
            urlList.AddRange(subcategoryUrl);
            using (var driver = new OpenQA.Selenium.Firefox.FirefoxDriver())
            {
                driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10));
                foreach (var url in urlList)
                {
                    driver.Url = url;
                    driver.Navigate();
                    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
                    wait.Until(x => x.FindElement(By.Id("GuidanceTypeLabel")).Text.Length>0);
                    var text = driver.FindElement(By.Id("GuidanceTypeLabel")).Text;
                    Console.WriteLine(text);
                    Assert.IsTrue(text == "Vulnerability");
                }
            }
        }
示例#2
0
 public static void Init(TestContext x)
 {
     OpenQA.Selenium.Firefox.FirefoxDriver fd = new OpenQA.Selenium.Firefox.FirefoxDriver();
     Browsers.Add(fd);
     OpenQA.Selenium.Chrome.ChromeDriver cd = new OpenQA.Selenium.Chrome.ChromeDriver();
     Browsers.Add(cd);
 }
示例#3
0
        internal static IWebDriver LaunchBrowser(Type browser)
        {
            switch (browser)
            {
            case Type.CHROME:
                Driver = new OpenQA.Selenium.Chrome.ChromeDriver();
                break;

            case Type.FIREFOX:
                Driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                break;

            case Type.IE:
                Driver = new OpenQA.Selenium.IE.InternetExplorerDriver();
                break;

            case Type.SAFARI:
                Driver = new OpenQA.Selenium.Safari.SafariDriver();
                break;

            default:
                throw new ApplicationException("No appropriate browser driver was provided.");
            }
            return(Driver);
        }
        /// <summary>
        /// construct a Selenium Action Manager with an Automation Engine
        /// </summary>
        /// <param name="automation">the Automation Engine</param>
        public SeleniumActionManager(abt.Automation automation, Browser browser)
            : base(automation)
        {
            switch (browser)
            {
                case Browser.Chrome:
                    {
                        OpenQA.Selenium.Chrome.ChromeDriverService service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                        service.HideCommandPromptWindow = true;
                        WebDriver = new OpenQA.Selenium.Chrome.ChromeDriver(service, new OpenQA.Selenium.Chrome.ChromeOptions());
                        break;
                    }
                case Browser.FireFox:
                    WebDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                    break;
                case Browser.Safari:
                    WebDriver = new OpenQA.Selenium.Safari.SafariDriver();
                    break;
                default:
                    WebDriver = new OpenQA.Selenium.IE.InternetExplorerDriver();
                    break;
            };
            WebDriver.Manage().Timeouts().ImplicitlyWait(new TimeSpan(0, 0, 30));

            RegisterAction(new ActionClick(WebDriver));
            RegisterAction(new ActionOpenURL(WebDriver));
            RegisterAction(new ActionRefresh(WebDriver));
            RegisterAction(new ActionGoBack(WebDriver));
        }
示例#5
0
 public static void Init(TestContext x)
 {
     OpenQA.Selenium.Firefox.FirefoxDriver fd = new OpenQA.Selenium.Firefox.FirefoxDriver();
     Browsers.Add(fd);
     OpenQA.Selenium.Chrome.ChromeDriver cd = new OpenQA.Selenium.Chrome.ChromeDriver();
     Browsers.Add(cd);
 }
示例#6
0
        public static void Main(string[] args)
        {
            using (var driver = new OpenQA.Selenium.Firefox.FirefoxDriver())
             {
                 // Go to the home page
                 driver.Navigate().GoToUrl("http://testing-ground.scraping.pro/login");

                 // Get the page elements
                 var userNameField = driver.FindElementById("usr");
                 var userPasswordField = driver.FindElementById("pwd");
                 var loginButton = driver.FindElementByXPath("//input[@value='Login']");

                 // Type user name and password
                 userNameField.SendKeys("admin");
                 userPasswordField.SendKeys("123456");

                 // and click the login button
                 loginButton.Click();

                 // Extract the text and save it into result.txt
                 var result = driver.FindElementByXPath("//div[@id='case_login']/h3").Text;
                 File.WriteAllText("result.txt", result);

                 // Take a screenshot and save it into screen.png
                 //driver.GetScreenshot().SaveAsFile(@"screen.png", ImageFormat.Png);
                 Thread.Sleep(1000);
                 driver.Quit();
             }
        }
        /// <summary>
        /// construct an ActionManager
        /// </summary>
        /// <param name="parent">the Automation object</param>
        public SeleniumActionManager(IAutomation parent, Browser browser)
            : base(parent)
        {
            switch (browser)
            {
                case Browser.Chrome:
                    {
                        OpenQA.Selenium.Chrome.ChromeDriverService service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                        service.HideCommandPromptWindow = true;
                        WebDriver = new OpenQA.Selenium.Chrome.ChromeDriver(service, new OpenQA.Selenium.Chrome.ChromeOptions());
                        break;
                    }
                case Browser.FireFox:
                    WebDriver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                    break;
                case Browser.Safari:
                    WebDriver = new OpenQA.Selenium.Safari.SafariDriver();
                    break;
                default:
                    WebDriver = new OpenQA.Selenium.IE.InternetExplorerDriver();
                    break;
            };
            WebDriver.Manage().Timeouts().ImplicitlyWait(WaitTime);

            RegisterAction(new ActionClick(WebDriver));
            RegisterAction(new ActionOpenURL(WebDriver));
            RegisterAction(new ActionRefresh(WebDriver));
            RegisterAction(new ActionGoBack(WebDriver));
            RegisterAction(new ActionEnter(WebDriver));

            RegisterAction(new ActionCheckControlProperty(WebDriver));
            RegisterAction(new ActionSet(WebDriver));
        }
示例#8
0
        public void Initialize()
        {
            RemoteWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();

            selenium = new WebDriverBackedSelenium(driver, "http://localhost/SiteStarter");

            selenium.Start();
            verificationErrors = new StringBuilder();
        }
        public void Initialize()
        {
            RemoteWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();

            selenium = new WebDriverBackedSelenium(driver, "http://localhost/SiteStarter");

            selenium.Start();
            verificationErrors = new StringBuilder();
        }
 public async Task <bool> ZseCheckIsTop10(string dionicaName)
 {
     using (var driver = new OpenQA.Selenium.Firefox.FirefoxDriver())
     {
         driver.Navigate().GoToUrl("https://www.zse.hr/");
         var top10Table = driver.FindElement(OpenQA.Selenium.By.XPath(@"//*[@id=""mainContainer""]/table/tbody/tr[1]/td/table/tbody/tr/td[2]/div[1]/div[1]/table"));
         var top10DionicarskihDrustva = top10Table.FindElements(OpenQA.Selenium.By.TagName("strong"));
         return(top10DionicarskihDrustva.Where(dd => dd.Text == dionicaName).Any());
     }
 }
示例#11
0
        public void Test1()
        {
            var webDriver = new OpenQA.Selenium.Firefox.FirefoxDriver().AddReportPortal();

            webDriver.Navigate().GoToUrl("https://www.nuget.org");

            webDriver.FindElement(By.Name("q")).SendKeys("ReportPortal.Extensions");
            webDriver.FindElement(By.ClassName("btn-search")).Click();

            webDriver.Quit();
        }
示例#12
0
        static void Main(string[] args)
        {
            IWebDriver browser = new OpenQA.Selenium.Firefox.FirefoxDriver();//1. Открыть браузер
            IWebDriver browser2 = new OpenQA.Selenium.Chrome.ChromeDriver();
                       
            Test test = new Test(browser);
            test.test();

            Test test2 = new Test(browser2);
            test2.test();
        }
        public void TestMethod1()
        {
            //Navegando com o Chrome
            using (IWebDriver driver = new OpenQA.Selenium.Chrome.ChromeDriver())
            {
                SearchAndNavigateTest(driver);
            }

            //Navegando com o Firefox
            using (IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver())
            {
                SearchAndNavigateTest(driver);
            }
        }
示例#14
0
        public void FirstSeleniumTest()
        {
            var driver = new OpenQA.Selenium.Firefox.FirefoxDriver();

            //var driver = new OpenQA.Selenium.Chrome.ChromeDriver();
            driver.Navigate().GoToUrl("http://www.google.pl");
            Assert.That(driver.Title, Is.EqualTo("Google"));
            var element = driver.FindElementById("gbqfq");

            element.SendKeys("google\n");
            var wait   = new OpenQA.Selenium.Support.UI.WebDriverWait(driver, TimeSpan.FromSeconds(10));
            var result = wait.Until(d => {
                return(d.PageSource.Contains("Wyszukiwarka stron WWW"));
            });

            Assert.IsTrue(result);
            driver.Quit();
        }
示例#15
0
        private QA.IWebDriver InitWebDriver()
        {
            QA.IWebDriver theDriver = null;
            switch (this.browser)
            {
            case Browsers.IE:
            {
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(_ieOptions);
            }; break;

            case Browsers.Chrome:
            {
                theDriver = new QA.Chrome.ChromeDriver();
            }; break;

            case Browsers.Firefox:
            {
                theDriver = new QA.Firefox.FirefoxDriver();
            }; break;

            case Browsers.Safari:
            {
                theDriver = new QA.Safari.SafariDriver();
            }; break;

            case Browsers.PhantomJS:
            {
                theDriver = new QA.PhantomJS.PhantomJSDriver();
            }; break;

            default:
            {
                QA.IE.InternetExplorerOptions _ieOptions = new QA.IE.InternetExplorerOptions();
                _ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true;
                theDriver = new QA.IE.InternetExplorerDriver(_ieOptions);
            }; break;
            }
            return(theDriver);
        }
示例#16
0
        private IWebDriver getCurrentDriver()
        {
            OpenQA.Selenium.Remote.RemoteWebDriver driver = null;

            switch (_browserType)
            {
            case API.Enumerations.BrowserType.InternetExplorer:
                driver = new OpenQA.Selenium.IE.InternetExplorerDriver();
                break;

            case API.Enumerations.BrowserType.Firefox:
                driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                break;

            case API.Enumerations.BrowserType.Chrome:
                driver = new OpenQA.Selenium.Chrome.ChromeDriver();
                break;
            }

            driver.Manage().Cookies.DeleteAllCookies();

            return(driver);
        }
示例#17
0
        /// <summary>
        /// Event when a grid cell is clicked
        /// If the cell happens to be from the Url column, it launches firefox, enters the url and 
        /// attempts to enter username and password provided for auto login
        /// Does this using selenium webdriver.
        /// Also updates color of currently selected row to red
        /// </summary>
        private void dgViewCredentials_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                ResetDataGridViewStyle();

                if (e.RowIndex != -1)
                {
                    dgViewCredentials.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
                    string url = dgViewCredentials.Rows[e.RowIndex].Cells[4].Value.ToString();

                    if (dgViewCredentials.CurrentCell.ColumnIndex.Equals(4) && !string.IsNullOrEmpty(url))
                    {
                        OpenQA.Selenium.IWebDriver driver = new OpenQA.Selenium.Firefox.FirefoxDriver();
                        driver.Navigate().GoToUrl(url);
                        driver.Manage().Window.Maximize();

                        string usernameField = string.Empty;;
                        string passwordField = string.Empty;
                        var allInputFields = driver.FindElements(OpenQA.Selenium.By.XPath("//input"));

                        foreach (var field in allInputFields)
                        {

                            if (string.IsNullOrEmpty(usernameField) &
                                (field.GetAttribute("type").Equals("text") || field.GetAttribute("type").Equals("email")) &
                                (!field.GetAttribute("title").Equals("search") & !field.GetAttribute("name").Equals("q") & !field.GetAttribute("name").Equals("search")))
                            {
                                usernameField = field.GetAttribute("name");

                            }

                            if (string.IsNullOrEmpty(passwordField) & field.GetAttribute("type").Equals("password"))
                            {
                                passwordField = field.GetAttribute("name");

                            }

                        }

                        /*
                        MessageBox.Show("Current fields\n" +
                                        "Username: "******"\n" +
                                        "Password:" + passwordField);
                         * */

                         OpenQA.Selenium.IWebElement searchInput = null;
                         if (!string.IsNullOrEmpty(usernameField))
                         {
                             searchInput = driver.FindElement(OpenQA.Selenium.By.Name(usernameField));
                             searchInput.SendKeys(dgViewCredentials.Rows[e.RowIndex].Cells[2].Value.ToString());
                         }

                         if (!string.IsNullOrEmpty(passwordField))
                         {
                             searchInput = driver.FindElement(OpenQA.Selenium.By.Name(passwordField));
                             searchInput.SendKeys(dgViewCredentials.Rows[e.RowIndex].Cells[3].Value.ToString());
                         }

                         if (!string.IsNullOrEmpty(usernameField) & !string.IsNullOrEmpty(passwordField))
                         {
                             searchInput.SendKeys(OpenQA.Selenium.Keys.Enter);
                         }

                         usernameField = string.Empty;
                         passwordField = string.Empty;

                         driver = null;

                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
示例#18
0
        public IWebDriver GetWebDriver(WebDriverParameters parameters)
        {
            IWebDriver driver = null;
            var desiredCaps = new DesiredCapabilities();

            foreach (var cap in parameters.capabilities)
            {
                desiredCaps.SetCapability(cap.Key, cap.GetValue());
            }
            //desiredCaps.SetCapability(CapabilityType.Platform, new Platform(GetPlatformTypeFromString(parameters.platform)));
            //desiredCaps.SetCapability(CapabilityType.BrowserName, parameters.browserName);
            //if (parameters.version != string.Empty)
            //{
            //    desiredCaps.SetCapability(CapabilityType.Version, parameters.version);
            //}
            var ieOptions = new OpenQA.Selenium.IE.InternetExplorerOptions();
            ieOptions.IgnoreZoomLevel = true;
            ieOptions.UnexpectedAlertBehavior = OpenQA.Selenium.IE.InternetExplorerUnexpectedAlertBehavior.Accept;

            var chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
            chromeOptions.AddAdditionalCapability("unexpectedAlertBehaviour", "Accept");

            switch (parameters.browserName.ToUpperInvariant())
            {
                case "CHROME":
                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeOptions);
                    break;
                case "ANDROIDCHROME":
                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeOptions);
                    break;
                case "IE":
                    driver = new OpenQA.Selenium.IE.InternetExplorerDriver(ieOptions);
                    break;
                case "FIREFOX":
                    driver = new OpenQA.Selenium.Firefox.FirefoxDriver(desiredCaps);
                    break;
            }

            //driver.S(CapabilityType.UNEXPECTED_ALERT_BEHAVIOUR, UnexpectedAlertBehaviour.ACCEPT);

            return driver;
        }
示例#19
0
        private void Form1_Shown(object sender, EventArgs e)
        {
            //Variaveis
            IWebDriver driver = null;
            int        ToRow  = 0;
            int        ToCol  = 0;
            string     munc   = string.Empty;
            string     uf     = string.Empty;

            try
            {
                #region browser

                string url = @"https://e-gov.betha.com.br/e-nota/pesquisa_prestadores.faces";

                Browser browser = (Browser)Enum.Parse(typeof(Browser), ConfigurationManager.AppSettings["selenium_webdriver"].ToString());

                switch (browser)
                {
                case Browser.Chrome:
                {
                    //Create FireFox Service
                    OpenQA.Selenium.Chrome.ChromeDriverService chromeService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                    chromeService.HideCommandPromptWindow = true;
                    chromeService.SuppressInitialDiagnosticInformation = true;
                    //Create FireFox Profile object
                    OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                    chromeOptions.AddArguments(string.Concat("--app=", url));
                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeService, chromeOptions);
                }
                break;

                case Browser.Edge:
                    driver = new OpenQA.Selenium.Edge.EdgeDriver();
                    break;

                case Browser.Firefox:
                {
                    //Create FireFox Service
                    OpenQA.Selenium.Firefox.FirefoxDriverService firefoxService = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService(string.Concat(Application.StartupPath, @"\Selenium\Firefox"));
                    firefoxService.HideCommandPromptWindow = true;
                    firefoxService.SuppressInitialDiagnosticInformation = true;
                    //Create FireFox Profile object
                    OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();
                    driver = new OpenQA.Selenium.Firefox.FirefoxDriver(firefoxService, firefoxOptions);
                    driver.Navigate().GoToUrl(url);
                }
                break;

                case Browser.InternetExplorer:
                {
                    //Create FireFox Service
                    OpenQA.Selenium.IE.InternetExplorerDriverService InternetExplorerService = OpenQA.Selenium.IE.InternetExplorerDriverService.CreateDefaultService(string.Concat(Application.StartupPath, @"\Selenium\InternetExplorerDriver"));
                    InternetExplorerService.HideCommandPromptWindow = true;
                    InternetExplorerService.SuppressInitialDiagnosticInformation = true;
                    //Create FireFox Profile object
                    OpenQA.Selenium.IE.InternetExplorerOptions InternetExplorerOptions = new OpenQA.Selenium.IE.InternetExplorerOptions();
                    driver = new OpenQA.Selenium.IE.InternetExplorerDriver(InternetExplorerService, InternetExplorerOptions);
                    driver.Navigate().GoToUrl(url);
                }
                break;

                case Browser.Opera:
                {
                    //Create FireFox Service
                    OpenQA.Selenium.Opera.OperaDriverService OperaService = OpenQA.Selenium.Opera.OperaDriverService.CreateDefaultService(string.Concat(Application.StartupPath, @"\Selenium\Opera"));
                    OperaService.HideCommandPromptWindow = true;
                    OperaService.SuppressInitialDiagnosticInformation = true;
                    //Create FireFox Profile object
                    OpenQA.Selenium.Opera.OperaOptions OperaOptions = new OpenQA.Selenium.Opera.OperaOptions();
                    driver = new OpenQA.Selenium.Opera.OperaDriver(OperaService, OperaOptions);
                    driver.Navigate().GoToUrl(url);
                }
                break;

                default:
                    throw new NotSupportedException(string.Format(System.Globalization.CultureInfo.CurrentCulture, "Driver {0} não suportado", browser));
                }

                if (driver == null)
                {
                    throw new Exception("WebDriver do Selenium não definido nas configurações");
                }

                #endregion browser

                //Aguarda processamento da página 5min
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));

                //Arquivo
                FileInfo fileInfo = new FileInfo(string.Format(@"{0}\Prestadores.xls", Application.StartupPath));
                if (fileInfo.Exists)
                {
                    fileInfo.Delete();
                }

                using (ExcelPackage package = new ExcelPackage(fileInfo))
                {
                    try
                    {
                        #region UF

                        for (int i = 1; i < driver.FindElement(By.Id("mainForm:estado")).FindElements(By.TagName("option")).Count; i++)
                        {
                            try
                            {
                                if (i != 11)
                                {
                                    continue;
                                }

                                //Variaveis
                                ToRow = 1;
                                ToCol = 8; //Total de colunas
                                munc  = string.Empty;
                                uf    = string.Empty;

                                System.Threading.Thread.Sleep(1500);

                                //Seleciona UF
                                driver.FindElement(By.Id("mainForm:estado")).FindElements(By.TagName("option"))[i].Click();
                                uf = driver.FindElement(By.Id("mainForm:estado")).FindElements(By.TagName("option"))[i].Text;

                                System.Threading.Thread.Sleep(500);

                                //Worksheet
                                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(uf.Trim());

                                #region Municipio

                                for (int j = 1; j < driver.FindElement(By.Id("mainForm:municipio")).FindElements(By.TagName("option")).Count; j++)
                                {
                                    try
                                    {
                                        //if(j != 61)
                                        //    continue;

                                        //Municipio
                                        driver.FindElement(By.Id("mainForm:municipio")).FindElements(By.TagName("option"))[j].Click();
                                        munc = driver.FindElement(By.Id("mainForm:municipio")).FindElements(By.TagName("option"))[j].Text;

                                        if (!driver.FindElement(By.Id("mainForm:master:messageSection:warn")).Displayed)
                                        {
                                            string html = driver.PageSource;
                                            if (!string.IsNullOrEmpty(html))
                                            {
                                                // Load From String
                                                var htmlDocument = new HtmlAgilityPack.HtmlDocument();
                                                htmlDocument.LoadHtml(html);

                                                bool blnPrestador = htmlDocument.GetElementbyId("mainForm:prestadores") == null ? false : true;

                                                do
                                                {
                                                    htmlDocument.LoadHtml(driver.PageSource);
                                                    blnPrestador = htmlDocument.GetElementbyId("mainForm:prestadores") == null ? false : true;
                                                } while (blnPrestador == false);

                                                var prestadores = htmlDocument.GetElementbyId("mainForm:prestadores");
                                                var tabela      = prestadores.SelectNodes("table");
                                                var linhas      = tabela.ElementAt(0).SelectNodes("tbody//tr");

                                                #region Add the headers row 1

                                                worksheet.Cells["A1"].Value = "Razão/Nome";
                                                worksheet.Cells["B1"].Value = "Logradouro";
                                                worksheet.Cells["C1"].Value = "Bairro";
                                                worksheet.Cells["D1"].Value = "Complemento";
                                                worksheet.Cells["E1"].Value = "CEP";
                                                worksheet.Cells["F1"].Value = "Email";
                                                worksheet.Cells["G1"].Value = "Telefone";
                                                worksheet.Cells["H1"].Value = "UF";
                                                worksheet.Cells["I1"].Value = "Municipio";

                                                //Format row header 1 style;
                                                using (var range = worksheet.Cells["A1:I1"])
                                                {
                                                    range.Style.Font.Bold        = true;
                                                    range.Style.Fill.PatternType = ExcelFillStyle.Solid;
                                                    range.Style.Font.Color.SetColor(Color.Black);
                                                    range.Style.Fill.BackgroundColor.SetColor(Color.FromArgb(198, 198, 198));
                                                    range.Style.VerticalAlignment   = ExcelVerticalAlignment.Center;
                                                    range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                                                }

                                                #endregion Add the headers row 1

                                                #region Add some items in the cells

                                                foreach (HtmlNode linha in linhas)
                                                {
                                                    ToRow++;

                                                    foreach (HtmlNode campos in linha.SelectNodes("td"))
                                                    {
                                                        if (linha.SelectNodes("td").ElementAt(0).ChildNodes.ElementAt(0).HasChildNodes)
                                                        {
                                                            worksheet.Cells[ToRow, 1].Value = ConverterCaracteresEspeciais(linha.SelectNodes("td").ElementAt(0).ChildNodes.ElementAt(0).FirstChild.InnerText);
                                                            worksheet.Cells[ToRow, 2].Value = linha.SelectNodes("td").ElementAt(0).ChildNodes.ElementAt(3).InnerText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
                                                            worksheet.Cells[ToRow, 3].Value = linha.SelectNodes("td").ElementAt(0).ChildNodes.ElementAt(5).InnerText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
                                                            worksheet.Cells[ToRow, 4].Value = linha.SelectNodes("td").ElementAt(0).ChildNodes.ElementAt(7).InnerText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
                                                            worksheet.Cells[ToRow, 5].Value = linha.SelectNodes("td").ElementAt(0).ChildNodes.ElementAt(9).InnerText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
                                                        }

                                                        if (linha.SelectNodes("td").ElementAt(1).HasChildNodes)
                                                        {
                                                            worksheet.Cells[ToRow, 6].Value = linha.SelectNodes("td").ElementAt(1).ChildNodes.ElementAt(0).InnerText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
                                                            worksheet.Cells[ToRow, 7].Value = linha.SelectNodes("td").ElementAt(1).ChildNodes.ElementAt(2).InnerText.Replace("\n", "").Replace("\t", "").Replace("\r", "").Trim();
                                                        }

                                                        string[] arr = uf.ToString().Split('-');

                                                        worksheet.Cells[ToRow, 8].Value = arr[0].Trim();
                                                        worksheet.Cells[ToRow, 9].Value = munc;
                                                    }
                                                }

                                                #endregion Add some items in the cells
                                            }
                                        }
                                    }
                                    catch (Exception ex) { throw; }
                                }

                                #endregion Municipio

                                #region Format type cells
                                //Format type cells
                                for (int fc = 0; fc < ToRow; fc++)
                                {
                                    //Row
                                    if (fc <= 1)
                                    {
                                        continue;
                                    }

                                    //Campos
                                    worksheet.Cells[fc, 1].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 2].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 3].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 4].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 5].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 6].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 7].Style.Numberformat.Format = "@";
                                    worksheet.Cells[fc, 8].Style.Numberformat.Format = "@";
                                }

                                #endregion Format type cells

                                if (ToRow == 1)
                                {
                                    worksheet = null;
                                    continue;
                                }

                                //Format the values
                                using (var range = worksheet.Cells[2, 1, ToRow, ToCol])
                                {
                                    range.Style.VerticalAlignment   = ExcelVerticalAlignment.Center;
                                    range.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                                }

                                //Create an autofilter for the range
                                worksheet.Cells[1, 1, ToRow, ToCol].AutoFilter = true;

                                //Excel line freeze
                                worksheet.View.FreezePanes(2, 1);

                                //Autofit columns for all cells
                                worksheet.Cells.AutoFitColumns(0);

                                //// Change the sheet view to show it in page layout mode
                                //worksheet.View.PageLayoutView = false;
                            }
                            catch { }
                        }

                        #endregion UF
                    }
                    catch (Exception ex)
                    {
                        if (driver != null)
                        {
                            driver.Dispose();
                        }
                    }
                    finally
                    {
                        // set some document properties
                        package.Workbook.Properties.Title = "Prestadore e-Notas";

                        // save our new workbook and we are done!
                        package.Save();
                    }
                }
            }
            catch (Exception)
            {
                if (driver != null)
                {
                    driver.Dispose();
                }
            }
            finally
            {
                if (driver != null)
                {
                    driver.Dispose();
                }
            }
        }
示例#20
0
 /// <summary>Starts a new Selenium testing session</summary>
 /// <param name="browser">Name of the browser : firefox, ie, chrome, phantomjs</param>
 /// <param name="baseUrl">The base URL</param>
 /// <param name="useLastSession">Optional - Try to use the previous session if the browser is still openned (Excel only)</param>
 /// <example>
 /// <code lang="vbs">	
 ///     WebDriver driver = New WebDriver()
 ///     driver.start "firefox", "http://www.google.com"
 ///     driver.open "/"
 /// </code>
 /// </example>
 public void start(string browser, String baseUrl = null, bool useLastSession = false) {
     if (useLastSession && CopyStaticDriver(baseUrl)) return;
     _isStartedRemotely = false;
     var dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
     DesiredCapabilities capa = new DesiredCapabilities(_capabilities);
     switch (browser.ToLower().Replace("*", "")) {
         case "firefox": case "ff":
             WebDriver = new OpenQA.Selenium.Firefox.FirefoxDriver(getFirefoxOptions());
             break;
         case "cr": case "chrome":
             ChromeDriverService crService = ChromeDriverService.CreateDefaultService(dir);
             crService.EnableVerboseLogging = false;
             crService.SuppressInitialDiagnosticInformation = true;
             crService.HideCommandPromptWindow = this._hideCommandPromptWindow;
             WebDriver = new OpenQA.Selenium.Chrome.ChromeDriver(crService, getChromeOptions());
             break;
         case "phantomjs": case "pjs":
             var pjsService = PhantomJSDriverService.CreateDefaultService(dir);
             pjsService.SuppressInitialDiagnosticInformation = true;
             pjsService.IgnoreSslErrors = true;
             pjsService.HideCommandPromptWindow = this._hideCommandPromptWindow;
             if(base._proxy != null)
                 pjsService.Proxy = base._proxy.HttpProxy;
             if(base._arguments != null)
                 pjsService.AddArguments(base._arguments);
             WebDriver = new OpenQA.Selenium.PhantomJS.PhantomJSDriver(pjsService, getPhantomJSOptions());
             break;
         case "internetexplorer": case "iexplore": case "ie":
         case "internetexplorer64": case "iexplore64": case "ie64":
             var ieService = OpenQA.Selenium.IE.InternetExplorerDriverService.CreateDefaultService(dir);
             ieService.SuppressInitialDiagnosticInformation = true;
             ieService.LoggingLevel = OpenQA.Selenium.IE.InternetExplorerDriverLogLevel.Error;
             ieService.HideCommandPromptWindow = this._hideCommandPromptWindow;
             WebDriver = new OpenQA.Selenium.IE.InternetExplorerDriver(ieService, getInternetExplorerOptions());
             break;
         case "safari": case "sa":
             WebDriver = new OpenQA.Selenium.Safari.SafariDriver(getSafariOptions());
             break;
         default:
             throw new ApplicationException("Browser <" + browser + "> is not available !  \nAvailable are Firefox, IE, Chrome, Safari and PhantomJS");
     }
     this.setTimeout(_timeout);
     if (!string.IsNullOrEmpty(baseUrl))
         _baseUrl = baseUrl.TrimEnd('/');
     _timerhotkey.Start();
 }
示例#21
0
        static void Main(string[] args)
        {
            try
            {
                ConsoleCmdLine   ccl            = new ConsoleCmdLine();
                CmdLineString    outputFileName = new CmdLineString("output-file", false, "Output File Name - defaults to SeleniumJasmineResults.xml");
                CmdLineString    chromeBaseDir  = new CmdLineString("chrome-path", false, @"Path to ChromeDriver.exe - defaults to c:\selenium\chromedriver_win32_2.2");
                CmdLineString    ieBaseDir      = new CmdLineString("ie-path", false, @"Path to IEDriverServer.exe - defaults to c:\selenium\IEDriverServer_x86_2.34.0");
                CmdLineString    inputUrlList   = new CmdLineString("input-url-file", false, "Input file containing urls to test - defaults to SpecRunnerList.txt");
                CmdLineParameter runChrome      = new CmdLineParameter("chrome", false, "Run Selenium with the chrome driver");
                CmdLineParameter runIE          = new CmdLineParameter("ie", false, "Run Selenium with the ie driver");
                CmdLineParameter runFireFox     = new CmdLineParameter("firefox", false, "Run Selenium with the FireFox driver");

                CmdLineParameter timeout     = new CmdLineParameter("timeout", false, "Timeout value (seconds) to wait for the tests to finish. defaults to 90.");
                CmdLineParameter reporter    = new CmdLineParameter("reporter", false, "Reporter type : jenkins | teamcity.  Defaults to teamcity reporter ");
                CmdLineParameter resultInput = new CmdLineParameter("reporter-input", false, "Reporter type : trivialreporter | logreporter.  Use trivial reporter for jasmine < 2.0 , use logreporter otherwise. ");


                ccl.RegisterParameter(outputFileName);
                ccl.RegisterParameter(chromeBaseDir);
                ccl.RegisterParameter(ieBaseDir);
                ccl.RegisterParameter(inputUrlList);
                ccl.RegisterParameter(runChrome);
                ccl.RegisterParameter(runIE);
                ccl.RegisterParameter(runFireFox);
                ccl.RegisterParameter(timeout);
                ccl.RegisterParameter(reporter);
                ccl.RegisterParameter(resultInput);
                ccl.Parse(args);


                string strOutputFileName     = !string.IsNullOrEmpty(outputFileName.Value) ? outputFileName.Value : "SeleniumTestRunner.xml";
                string strChromeBaseDir      = !string.IsNullOrEmpty(chromeBaseDir.Value) ? chromeBaseDir.Value : @"E:\source\github\selenium-jasmine-runner\chromedriver_win32_2.2";
                string strIEBaseDir          = !string.IsNullOrEmpty(ieBaseDir.Value) ? ieBaseDir.Value : @"E:\source\github\selenium-jasmine-runner\IEDriverServer_x64_2.34.0";
                string strSpecRunnerListFile = !string.IsNullOrEmpty(inputUrlList.Value) ? inputUrlList.Value : "SpecRunnerList.txt";
                string strReporter           = !string.IsNullOrEmpty(reporter.Value) ? reporter.Value : "teamcity";

                string strInput = !string.IsNullOrEmpty(resultInput.Value) ? resultInput.Value : "logreporter";

                short timeoutValue = 90;
                if (!string.IsNullOrEmpty(timeout.Value))
                {
                    Int16.TryParse(timeout.Value, out timeoutValue);
                }

                TestSuites testSuites = new TestSuites(TestReporterFactory.GetTestReporter(strReporter));

                List <string> strFileList = new List <string> ();
                using (FileStream fs = new FileStream(strSpecRunnerListFile, FileMode.Open, FileAccess.Read))
                {
                    StreamReader streamReader = new StreamReader(fs);

                    string strLine = streamReader.ReadLine();

                    while (!string.IsNullOrEmpty(strLine))
                    {
                        strFileList.Add(strLine);
                        strLine = streamReader.ReadLine();
                    }
                }

                if (runFireFox.Exists)
                {
                    using (var firefoxDriver = new OpenQA.Selenium.Firefox.FirefoxDriver())
                    {
                        foreach (string strSpecRunner in strFileList)
                        {
                            string strPageName = strSpecRunner.Substring(strSpecRunner.LastIndexOf('/') + 1);
                            if (strPageName.IndexOf('.') > 0)
                            {
                                strPageName = strPageName.Substring(0, strPageName.IndexOf('.'));
                            }

                            if (strInput == "logreporter")
                            {
                                RunAllJasmineTestsAndReport_LogReporter(firefoxDriver, timeoutValue, strSpecRunner,
                                                                        strPageName,
                                                                        "Chrome", ref testSuites);
                            }
                            else
                            {
                                RunAllJasmineTestsAndReportTrivialReporter(firefoxDriver, timeoutValue, strSpecRunner,
                                                                           strPageName, "FireFox", ref testSuites);
                            }
                        }
                    }
                }

                if (runChrome.Exists)
                {
                    using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver(strChromeBaseDir))
                    {
                        foreach (string strSpecRunner in strFileList)
                        {
                            string strPageName = strSpecRunner.Substring(strSpecRunner.LastIndexOf('/') + 1);
                            if (strPageName.IndexOf('.') > 0)
                            {
                                strPageName = strPageName.Substring(0, strPageName.IndexOf('.'));
                            }

                            if (strInput == "logreporter")
                            {
                                RunAllJasmineTestsAndReport_LogReporter(driver, timeoutValue, strSpecRunner, strPageName,
                                                                        "Chrome", ref testSuites);
                            }
                            else
                            {
                                RunAllJasmineTestsAndReportTrivialReporter(driver, timeoutValue, strSpecRunner,
                                                                           strPageName, "Chrome", ref testSuites);
                            }
                        }
                    }
                }

                if (runIE.Exists)
                {
                    InternetExplorerOptions options = new InternetExplorerOptions();
                    options.EnableNativeEvents = false;
                    options.EnsureCleanSession = true;

                    using (var driver = new OpenQA.Selenium.IE.InternetExplorerDriver(strIEBaseDir))

                    {
                        foreach (string strSpecRunner in strFileList)
                        {
                            string strPageName = strSpecRunner.Substring(strSpecRunner.LastIndexOf('/') + 1);
                            if (strPageName.IndexOf('.') > 0)
                            {
                                strPageName = strPageName.Substring(0, strPageName.IndexOf('.'));
                            }

                            if (strInput == "logreporter")
                            {
                                RunAllJasmineTestsAndReport_LogReporter(driver, timeoutValue, strSpecRunner, strPageName, "IE", ref testSuites);
                            }
                            else
                            {
                                RunAllJasmineTestsAndReportTrivialReporter(driver, timeoutValue, strSpecRunner, strPageName, "IE", ref testSuites);
                            }
                        }
                    }
                }



                Console.WriteLine("-----------");

                if (strInput != "logreporter")
                {
                    testSuites.WriteToConsole();

                    using (FileStream fs = new FileStream(strOutputFileName, FileMode.Create, FileAccess.Write))
                    {
                        StreamWriter streamWriter = new StreamWriter(fs);

                        testSuites.WriteToStream(streamWriter);

                        streamWriter.Flush();
                    }

                    using (StreamWriter sw = new StreamWriter(Console.OpenStandardOutput()))
                    {
                        sw.AutoFlush = true;
                        testSuites.WriteToStream(sw);
                        sw.Flush();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("");
                Console.WriteLine("Unhandled Exception " + ex.ToString());
                Console.WriteLine("");
                Console.WriteLine(ex.ToString());
                throw ex;
            }
        }
示例#22
0
        /// <summary>
        /// Método sem recaptcha
        /// </summary>
        /// <param name="linhaDigitavel">Linha digitável do boleto</param>
        public static void Consultar(string cnpj, string id, string linhaDigitavel, string cpfCnpjPagador)
        {
            IWebDriver driver = null;

            try
            {
                //Trata linha digitável
                linhaDigitavel = linhaDigitavel.Replace(".", string.Empty).Replace(" ", string.Empty);

                #region Diretório / Arquivos

                DirectoryInfo directoryInfo = new System.IO.DirectoryInfo("Boletos");
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                directoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfo.FullName, cnpj));
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                directoryInfo = new System.IO.DirectoryInfo(Path.Combine(directoryInfo.FullName, string.Format("{0:yyyy-MM-dd}", DateTime.Now)));
                if (!directoryInfo.Exists)
                {
                    directoryInfo.Create();
                }

                FileInfo fileInfo = new System.IO.FileInfo(Path.Combine(directoryInfo.FullName, "Boletos.pdf"));
                if (fileInfo.Exists)
                {
                    fileInfo.Delete();
                }

                #endregion Diretório / Arquivo

                #region Chrome - Options

                if (ConfigurationManager.AppSettings["selenium_webdriver"] == "chrome")
                {
                    OpenQA.Selenium.Chrome.ChromeDriverService chromeService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                    chromeService.HideCommandPromptWindow = true;
                    chromeService.SuppressInitialDiagnosticInformation = true;

                    OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                    chromeOptions.AddUserProfilePreference("download.default_directory", directoryInfo.FullName);
                    chromeOptions.AddUserProfilePreference("download.prompt_for_download", false);
                    chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true");

                    //Disable
                    chromeOptions.AddArgument("disable-infobars");
                    //chromeOptions.AddArgument("headless");Utilizado para suprimir a exibição da janela do chrome

                    driver = new OpenQA.Selenium.Chrome.ChromeDriver(chromeService, chromeOptions);
                }

                #endregion Chrome - Options

                #region Firefox - Options

                if (ConfigurationManager.AppSettings["selenium_webdriver"] == "firefox")
                {
                    /*
                     * Firefoz config options
                     *
                     * http://kb.mozillazine.org/About:config_entries#Browser.
                     * */

                    //Create FireFox Service
                    OpenQA.Selenium.Firefox.FirefoxDriverService firefoxService = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService();
                    firefoxService.HideCommandPromptWindow = true;
                    firefoxService.SuppressInitialDiagnosticInformation = true;

                    //Create FireFox Profile object
                    OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();

                    //Set location to store files after downloading.
                    firefoxOptions.SetPreference("browser.download.folderList", 2);
                    firefoxOptions.SetPreference("browser.helperApps.alwaysAsk.force", false);
                    firefoxOptions.SetPreference("browser.download.manager.focusWhenStarting", false);
                    firefoxOptions.SetPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
                    firefoxOptions.SetPreference("pdfjs.disabled", true);
                    firefoxOptions.SetPreference("browser.download.dir", directoryInfo.FullName);

                    //Set Preference to not show file download confirmation dialogue using MIME types Of different file extension types.
                    firefoxOptions.SetPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");

                    // Use this to disable Acrobat plugin for previewing PDFs in Firefox (if you have Adobe reader installed on your computer)
                    firefoxOptions.SetPreference("plugin.scan.Acrobat", "99.0");
                    firefoxOptions.SetPreference("plugin.scan.plid.all", false);

                    //Pass profile parameter In webdriver to use preferences to download file.
                    driver = new OpenQA.Selenium.Firefox.FirefoxDriver(firefoxService, firefoxOptions);
                }

                #endregion Firefox - Options

                if (driver == null)
                {
                    throw new Exception("WebDriver do Selenium não definido nas configurações");
                }

                driver.Navigate().GoToUrl("https://www.itau.com.br/servicos/boletos/atualizar/");

                //Aguarda processamento da página
                WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60));

                //Textbox
                var elem = wait.Until(d =>
                {
                    try
                    {
                        var ele = d.FindElement(By.Id("representacaoNumerica"));
                        return(ele.Displayed ? ele : null);
                    }
                    catch (UnhandledAlertException)
                    {
                        return(null);
                    }
                    catch (StaleElementReferenceException)
                    {
                        return(null);
                    }
                    catch (NoSuchElementException)
                    {
                        return(null);
                    }
                });


                //Preenche os dados da pesquisa
                driver.FindElement(By.Id("representacaoNumerica")).SendKeys(linhaDigitavel);
                driver.FindElement(By.Id("txtDocumentoSacado")).SendKeys(cpfCnpjPagador);
                driver.FindElement(By.Id("btnProximo")).Click();

                //Aguarda
                System.Threading.Thread.Sleep(2500);

                //Acessa aba aerta
                driver.SwitchTo().Window(driver.WindowHandles.Last());

                //Botão de cownload
                elem = wait.Until(d =>
                {
                    try
                    {
                        var ele = d.FindElement(By.Name("frmPDF"));
                        return(ele.Displayed ? ele : null);
                    }
                    catch (UnhandledAlertException)
                    {
                        return(null);
                    }
                    catch (StaleElementReferenceException)
                    {
                        return(null);
                    }
                    catch (NoSuchElementException)
                    {
                        return(null);
                    }
                });

                //Download
                ((IJavaScriptExecutor)driver).ExecuteScript("javascript:document.frmPDF.submit();");

                //Aguarda
                System.Threading.Thread.Sleep(3000);

                //Renomear
                fileInfo.Refresh();
                if (fileInfo.Exists)
                {
                    fileInfo.MoveTo(Path.Combine(directoryInfo.FullName, string.Format("{0}.pdf", id)));
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (driver != null)
                {
                    driver.Dispose();
                }
            }
        }
示例#23
0
        private void btnRun_Click(object sender, EventArgs e)
        {
            ConfigCrawlerSelenium config = this.GetConfig();

            Task.Factory.StartNew(() =>
            {
                using (OpenQA.Selenium.Firefox.FirefoxDriver fireFoxDriver = new OpenQA.Selenium.Firefox.FirefoxDriver())
                {
                    int countVisited            = 0;
                    Uri rootLink                = new Uri(config.RootLInk);
                    HashSet <long> crcVisited   = new HashSet <long>();
                    Queue <string> queueLink    = new Queue <string>();
                    HashSet <long> productLinks = new HashSet <long>();
                    queueLink.Enqueue(config.RootLInk);

                    foreach (var str in config.QueueInit)
                    {
                        queueLink.Enqueue(str);
                    }
                    while (queueLink.Count > 0)
                    {
                        string urlCurrent = queueLink.Dequeue();
                        fireFoxDriver.Url = urlCurrent;
                        Thread.Sleep(1000);
                        this.ShowLog(string.Format("GetJob: {0}", urlCurrent));
                        countVisited++;
                        var nodeLinks = fireFoxDriver.FindElementsByTagName("a");
                        if (nodeLinks != null)
                        {
                            foreach (var node in nodeLinks)
                            {
                                string linkNew = node.GetAttribute("href");
                                if (!string.IsNullOrEmpty(linkNew))
                                {
                                    linkNew    = QT.Entities.Common.GetAbsoluteUrl(linkNew, rootLink);
                                    long IDNew = QT.Entities.Common.CrcProductID(linkNew);
                                    if (!crcVisited.Contains(IDNew) && QT.Entities.Common.CheckRegex(linkNew, config.RegexToQueue, null, false))
                                    {
                                        crcVisited.Add(IDNew);
                                        queueLink.Enqueue(linkNew);
                                    }
                                }
                            }
                        }

                        var nodeLinkFindProduct = fireFoxDriver.FindElementsByXPath(config.XPathProduct[0]);
                        if (nodeLinkFindProduct != null)
                        {
                            foreach (var nodeData in nodeLinkFindProduct)
                            {
                                string linkNew = nodeData.GetAttribute("href");
                                long IDNew     = QT.Entities.Common.CrcProductID(linkNew);
                                linkNew        = QT.Entities.Common.GetAbsoluteUrl(linkNew, rootLink);
                                if (!productLinks.Contains(IDNew) &&
                                    QT.Entities.Common.CheckRegex(linkNew, config.RegexAcceptProduct, null, false))
                                {
                                    productLinks.Add(IDNew);
                                    this.ShowLinkProduct(linkNew);
                                }
                            }
                        }

                        this.ShowLog(string.Format("Queue: {0} CrcAdded: {1} Visited: {2}", queueLink.Count, crcVisited.Count, countVisited++));
                    }
                }
            });
        }