public CareerRetriever(string geckoPath, IBrowsingContext br = null)
        {
            var firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();

            firefoxOptions.AddArgument("-headless");
            driver = new OpenQA.Selenium.Firefox.FirefoxDriver(geckoPath, firefoxOptions);
        }
Esempio n. 2
0
        public static void RegisterWebDriver(this DIContainer diContainer)
        {
            var capabilities = new OpenQA.Selenium.Firefox.FirefoxOptions().ToCapabilities();
            var driver       = new RemoteWebDriver(TestSettings.SeleniumHubAddress, capabilities);

            diContainer.Register <IWebDriver>(driver);
        }
Esempio n. 3
0
        private void EnterOnSite()
        {
            if (selectBrowser == 0)
            {
                var serv = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService();
                serv.HideCommandPromptWindow = true;
                var options = new OpenQA.Selenium.Chrome.ChromeOptions();
                if (!visBr.Checked)
                {
                    options.AddArgument("--window-position=-32000,-32000");
                }



                //  Brow.SwitchTo
                Brow = new OpenQA.Selenium.Chrome.ChromeDriver(serv, options);
            }
            else
            {
                var serv = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService();// Chrome.ChromeDriverService.CreateDefaultService();
                serv.HideCommandPromptWindow = true;
                var options = new OpenQA.Selenium.Firefox.FirefoxOptions();
                if (!visBr.Checked)
                {
                    options.AddArgument("--window-position=-32000,-32000");
                }


                var pos = !visBr.Checked? new Point(32000, 32000): new Point(0, 0);

                Brow = new OpenQA.Selenium.Firefox.FirefoxDriver(serv, options, TimeSpan.FromSeconds(30));
                Brow.Manage().Window.Position = pos;
            }

            //Brow.Manage().Timeouts().ImplicitlyWait( ();
            //Brow.Manage().Window.Size.Heig
            WebDriverWait wait = new WebDriverWait(Brow, TimeSpan.FromSeconds(10));

            //WebDriverWait wait = new WebDriverWait(driver, 10);
            Brow.Navigate().GoToUrl("https://bitrix24.net.ua/");

            //selivanovsky.i
            //    silvergraf


            IWebElement log = wait.Until(ExpectedConditions.ElementIsVisible(By.Name("USER_LOGIN")));

            log.SendKeys(login);
            IWebElement pas = Brow.FindElement(By.Name("USER_PASSWORD"));

            pas.SendKeys(pasword + OpenQA.Selenium.Keys.Enter);
            System.Threading.Thread.Sleep(selectBrowser == 0?700:5000);

            Brow.Close();
            Brow.Dispose();
            Loger.SetLog(login);
        }
        public void ExampleTestUsingRemoteWebDriverWithFirefoxOptions()
        {
            OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();

            this.driver = new RemoteWebDriver(driverOptions: firefoxOptions);

            this.driver.Navigate().GoToUrl("https://example.testproject.io");
            this.driver.FindElement(By.CssSelector("#name")).SendKeys("John Smith");
            this.driver.FindElement(By.CssSelector("#password")).SendKeys("12345");
            this.driver.FindElement(By.CssSelector("#login")).Click();

            Assert.IsTrue(this.driver.FindElement(By.CssSelector("#greetings")).Displayed);
        }
        public ICapabilities GetCapabilitiesFromBrowserName(string browserName, string browserVersion, string platformName, Dictionary <string, object> optionalCapabilities = null)
        {
            optionalCapabilities = optionalCapabilities ?? new Dictionary <string, object>();
            DriverOptions browserOptions;

            switch (browserName)
            {
            case "firefox":
                browserOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();
                break;

            case "safari":
                browserOptions = new OpenQA.Selenium.Safari.SafariOptions();
                break;

            case "internet explorer":
                browserOptions = new OpenQA.Selenium.IE.InternetExplorerOptions();
                break;

            case "microsoft edge":
                browserOptions = new OpenQA.Selenium.Edge.EdgeOptions();
                break;

            default:
                browserOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                break;
            }

            browserOptions.BrowserVersion = browserVersion;
            browserOptions.PlatformName   = platformName;
            var cloudOptions = new Dictionary <string, object>();

            foreach (var optionalCapability in optionalCapabilities)
            {
                cloudOptions.Add(optionalCapability.Key, optionalCapability.Value);
            }

            cloudOptions.Add("username", this.username);
            cloudOptions.Add("password", this.authkey);
            browserOptions.AddAdditionalOption("cbt:options", cloudOptions);
            return(browserOptions.ToCapabilities());
        }
Esempio n. 6
0
        public IWebDriver CreateDriver()
        {
            string argumentLanguage = string.Format("--lang={0}", AppSettings.Settings.Locale);

            switch (AppSettings.Settings.Browser)
            {
            case Names.Chrome:
                OpenQA.Selenium.Chrome.ChromeOptions chromeOptions = new OpenQA.Selenium.Chrome.ChromeOptions();
                chromeOptions.AddArguments(argumentLanguage);
                return(new ChromeDriver(chromeOptions));

            case Names.FireFox:
                OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();
                firefoxOptions.AddArguments(argumentLanguage);
                return(new OpenQA.Selenium.Firefox.FirefoxDriver());

            default:
                throw new ArgumentException($"Browser not yet implemented: {AppSettings.Settings.Browser}");
            }
        }
Esempio n. 7
0
 public void StartBrowser()
 {
     OpenQA.Selenium.Firefox.FirefoxOptions firefoxOptions = new OpenQA.Selenium.Firefox.FirefoxOptions();
     firefoxOptions.AddArgument("-headless");
     this.driver = new FirefoxDriver(firefoxOptions: firefoxOptions, projectName: "CI - C#");
 }
Esempio n. 8
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();
                }
            }
        }
Esempio n. 9
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();
                }
            }
        }
Esempio n. 10
0
        private void button1_Click(object sender, EventArgs e)
        {
            UserAgent                = UserAgentTextBox.Text;
            button1.Enabled          = false;
            UserAgentTextBox.Enabled = false;

            OpenQA.Selenium.Firefox.FirefoxProfile profile = new OpenQA.Selenium.Firefox.FirefoxProfile();
            OpenQA.Selenium.Firefox.FirefoxOptions option  = new OpenQA.Selenium.Firefox.FirefoxOptions();
            profile.SetPreference("general.useragent.override", UserAgent);
            option.Profile = profile;
            Browser        = new OpenQA.Selenium.Firefox.FirefoxDriver(option);

            Browser.Manage().Window.Maximize();
            Browser.Navigate().GoToUrl("https://www.instagram.com/");
            Browser.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10);

            //----------------эл.адрес----------------
            IWebElement email       = Browser.FindElement(By.Name("emailOrPhone"));
            string      str_email_1 = RandomString(11, "LetterAndNumber");
            string      str_email_2 = "@" + "yandex.ru";
            string      str_email   = str_email_1 + str_email_2;

            SendToPage(email, str_email_1);
            SendToPage(email, str_email_2);
            //антиБОТ
            System.Threading.Thread.Sleep(1000);

            //----------------имя и фамилия----------------
            IWebElement name       = Browser.FindElement(By.Name("fullName"));
            string      str_name_1 = RandomString(7, "Letter");
            string      str_name_2 = " ";
            string      str_name_3 = RandomString(8, "Letter");
            string      str_name   = str_name_1 + str_name_2 + str_name_3;

            SendToPage(name, str_name_1);
            SendToPage(name, str_name_2);
            SendToPage(name, str_name_3);
            //антиБОТ
            System.Threading.Thread.Sleep(1000);

            //----------------имя пользователя----------------
            IWebElement username       = Browser.FindElement(By.Name("username"));
            string      str_username_1 = RandomString(5, "LetterAndNumber");
            string      str_username_2 = RandomString(5, "LetterAndNumber");
            string      str_username   = str_username_1 + str_username_2;

            SendToPage(username, str_username_1);
            SendToPage(username, str_username_2);
            //антиБОТ
            System.Threading.Thread.Sleep(1000);

            //----------------пароль----------------
            IWebElement password       = Browser.FindElement(By.Name("password"));
            string      str_password_1 = RandomString(2, "LetterAndNumber");
            string      str_password_2 = RandomString(4, "LetterAndNumber");
            string      str_password_3 = RandomString(4, "LetterAndNumber");
            string      str_password   = str_password_1 + str_password_2 + str_password_3;

            SendToPage(password, str_password_1);
            SendToPage(password, str_password_2);
            SendToPage(password, str_password_3);
            //антиБОТ
            System.Threading.Thread.Sleep(10304);

            password.SendKeys(OpenQA.Selenium.Keys.Enter);

            //----------------вывод в программу----------------
            textBox1.AppendText("Эл. адрес: " + str_email + "\n");
            textBox1.AppendText("Имя и Файмилия: " + str_name + "\n");
            textBox1.AppendText("Имя пользователя: " + str_username + "\n");
            textBox1.AppendText("Пароль: " + str_password + "\n");
            //----------------вывод в файл----------------
            fout.WriteLine("Эл. адрес: " + str_email + "\n");
            fout.WriteLine("Имя и Файмилия: " + str_name + "\n");
            fout.WriteLine("Имя пользователя: " + str_username + "\n");
            fout.WriteLine("Пароль: " + str_password + "\n");


            button3.Enabled = true;
        }