public static void Init() { Host = new HostBuilder() .ConfigureServices((hostContext, services) => { services .AddPomSelenium(autoGeneratePages: true) .AddSingleton <IWebDriver>(_ => { var options = new ChromeOptions(); options.AddArgument("--disable-notifications"); options.AddArgument("--disable-infobars"); options.AddArgument("--ignore-certificate-errors"); options.AddArgument("--disable-popup-blocking"); options.AddArgument("--disable-cache"); options.AddArgument("--disable-cached-picture-raster"); options.AddArgument("--disable-application-cache"); options.AddArgument("--disk-cache-size=0"); options.AddArgument("--headless"); var service = ChromeDriverService.CreateDefaultService(); service.HideCommandPromptWindow = true; var driver = new ChromeDriver(service, options); CurrentDomain.ProcessExit += (s, e) => driver?.Dispose(); return(driver); }); services.AddSingleton(s => s.AddPage <Page>()); services.AddSingleton(s => s.AddPage <PageActions>()); }).Build(); }
public void Dispose() { _driver?.Close(); _driver?.Dispose(); _token?.Cancel(); _task?.Wait(); _task?.Dispose(); }
public void Dispose() { if (_loginSuceeded) { Logout(); } _driver?.Dispose(); Directory.Delete(_downloadDirectory, true); }
public void Dispose() { if (_driver != null) { var screenshot = _driver.GetScreenshot(); screenshot.SaveAsFile("last-view.png"); _logger.LogInformation($"Last page url: {_driver.Url}"); } _driver?.Close(); _driver?.Dispose(); }
public BrowserSession AndSubmit() { try { NavigateToOpenTabs(); SetWaiter(); SetTableNumber(); Submit(); return(new BrowserSession(_chromeDriver)); } catch (NoSuchElementException) { _chromeDriver?.Dispose(); throw; } }
public ETrade10(IOAuthService oauthService, IWebDriver webDriver) { OAuthSvc = oauthService; if (webDriver == null) { try { var options = new ChromeOptions(); options.AddArgument("--headless"); WebDriver = new ChromeDriver(System.Environment.CurrentDirectory, options); } catch { WebDriver?.Dispose(); WebDriver = null; } } else { WebDriver = webDriver; WebDriver.Manage().Window.Minimize(); } }
public void TestEnd() { driver.Close(); driver.Dispose(); }
public CurrencyRate ScrapeCurrencyRate(CurrencyRate currencyRate) //This is the method that does the hard work. //It goes to each website and simulates user interactions to get values. { try { var chromeOptions = new ChromeOptions(); chromeOptions.AddArguments("--headless", "--no-sandbox", "--disable-dev-shm-usage", "--window-size=1920,1080", "--start-maximized"); using (var browserdriver = new ChromeDriver(chromeOptions)) { browserdriver.Navigate().GoToUrl(currencyRate.bankurl); //go to the url if (currencyRate.needclick) { //wait before clicking (Explicitly) var wait = new WebDriverWait(browserdriver, TimeSpan.FromSeconds(3)); wait.Until(drv => drv.FindElement(By.XPath(currencyRate.xpathtoclick))).Click(); //var buttontoclick = browserdriver.FindElement(By.XPath(currencyRate.xpathtoclick)); //buttontoclick.Click(); } string[] currencyrates = new string[2]; if (currencyRate.currencyisinputfield) //Self explanatory, but this basically checks if it is an input field so that it gets the "Value" instead of //the "Text" which would give an exception. { if (currencyRate.currencyisplaceholder) { currencyRate.buyrate = browserdriver.FindElement(By.XPath(currencyRate.xpathstocurrency[0])).GetAttribute("placeholder"); currencyRate.sellrate = browserdriver.FindElement(By.XPath(currencyRate.xpathstocurrency[1])).GetAttribute("placeholder"); } else //Differentiate between input placeholder & value { currencyRate.buyrate = browserdriver.FindElement(By.XPath(currencyRate.xpathstocurrency[0])).GetAttribute("value"); currencyRate.sellrate = browserdriver.FindElement(By.XPath(currencyRate.xpathstocurrency[1])).GetAttribute("value"); } } else { var buyrateinpage = browserdriver.FindElement(By.XPath(currencyRate.xpathstocurrency[0])); var sellrateinpage = browserdriver.FindElement(By.XPath(currencyRate.xpathstocurrency[1])); //Format if (currencyRate.shouldformat) { string[] separatedText = buyrateinpage.Text.Split('/'); currencyRate.buyrate = TrimString(separatedText[0]); currencyRate.sellrate = TrimString(separatedText[1]); } else { if (buyrateinpage.Text != "" || sellrateinpage.Text != "") { currencyRate.buyrate = TrimString(buyrateinpage.Text); currencyRate.sellrate = TrimString(sellrateinpage.Text); //Trim all the strings of their whitespace so that rates are kept very nicely. } else { currencyRate.buyrate = TrimString(buyrateinpage.GetAttribute("textContent")); currencyRate.sellrate = TrimString(sellrateinpage.GetAttribute("textContent")); } } } browserdriver.Close(); browserdriver.Dispose(); browserdriver.Quit(); Console.WriteLine("Closing BrowserDriver"); } Console.WriteLine(currencyRate.bankname + " Buys at: " + currencyRate.buyrate + " | Sells at: " + currencyRate.sellrate); return(currencyRate); } catch (Exception e) { Console.WriteLine("Exception occurred in a scraping. Sending Empty value, Trying again Later."); Console.WriteLine(e.ToString()); return(currencyRate); } }
public AuBicpBotController(string[] args) { //C:\Projetos\AuBicpBot\trunk\01-Implementacao\01 - Fontes\AuBicpBot //C:\Projetos\AuBicpBot\trunk\01-Implementacao\01 - Fontes\AuBicpBot\bin\Debug\netcoreapp2.1\ //driver = new ChromeDriver(); // m driver = new ChromeDriver(caminhoDriver); driver.Navigate().GoToUrl("http://10.64.0.152:8080/bicp/"); //Thread.Sleep(3000); driver.Manage().Window.Maximize(); IWebElement campoLogin = driver.FindElement(By.Id("userid")); IWebElement campoSenha = driver.FindElement(By.Id("pwd")); // id da do captcha a ser quebrado e recortado IWebElement campoiMG = driver.FindElement(By.Id("rdImg")); IWebElement campoCaptcha = driver.FindElement(By.Id("randImg")); IWebElement BtnSubmit = driver.FindElement(By.Id("logBtn")); this.CreateWorkDir(); #region Capiturar a imagem da tela e tratar o captcha try { Screenshot screenshot = ((ITakesScreenshot)driver).GetScreenshot(); screenshot.SaveAsFile(this.WORK_PATH + "\\ImgParacaptcha.png", ScreenshotImageFormat.Png); using (Image img = Bitmap.FromFile(this.WORK_PATH + "\\ImgParacaptcha.png")) { Rectangle rect = new Rectangle(); if (campoiMG != null) { int width = campoiMG.Size.Width; int height = campoiMG.Size.Height; Point p = campoiMG.Location; rect = new Rectangle(p.X, p.Y, width, height); } Bitmap bmpImage = new Bitmap(img); var cropedImag = bmpImage.Clone(rect, bmpImage.PixelFormat); cropedImag.Save(this.WORK_PATH + "\\captcha.png"); } #endregion string captcha_plain = this.DecodeCaptcha(); campoLogin.SendKeys("BRASILCENTER"); campoSenha.SendKeys("Center12"); campoCaptcha.SendKeys(captcha_plain); BtnSubmit.Submit(); //WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); //wait.Until((d) => d.FindElement(By.Id("sysMenu")) != null); IWebElement btn1575 = driver.FindElement(By.XPath(@"//*[@id='ext - gen29']/div[6]/table/tbody/tr[1]/td[3]/div/a")); btn1575.Click(); //driver.SwitchTo().Frame(driver.FindElement(By.XPath("//*[@id='topSysFrame']"))); IWebElement topMenuLink = driver.FindElement(By.Id("topMenuLink")); topMenuLink.Click(); IWebElement menuActBg = driver.FindElement(By.ClassName("menuActBg")); menuActBg.Click(); //IWebElement btnMenu = driver.FindElement(By.Id("sysMenu"));// XPath->//*[@id='sysMenu'] var element = driver.FindElement(By.Id("sysMenu")); //menuListName //mainMenu //topSysFrame Actions actions = new Actions(driver); actions.MoveToElement(element).Build().Perform(); Thread.Sleep(2000); //actions.Perform(); // var element = driver.FindElement(By.Id("sysMenu")); //menuListName //mainMenu //topSysFrame // Actions actions = new Actions(driver); // actions.MoveToElement(element); // actions.Perform(); // IWebElement btnMenutest = driver.FindElement(By.Id("sysMenu")); // btnMenutest.SendKeys(Keys.Enter); } catch (Exception e) { Console.WriteLine(e); driver.Close(); driver.Dispose(); } //driver.Close(); //driver.Dispose(); }
static void Main(string[] args) { List <Record> Records = new List <Record>(); List <Record> Importable = new List <Record>(); List <Record> cases = new List <Record>(); string basePath = AppDomain.CurrentDomain.BaseDirectory; var chromeOptions = new ChromeOptions(); chromeOptions.AddUserProfilePreference("download.default_directory", basePath); chromeOptions.AddUserProfilePreference("intl.accept_languages", "nl"); chromeOptions.AddUserProfilePreference("disable-popup-blocking", "true"); wait: Console.WriteLine("System going to wait ..."); while (true) { string wait = DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString(); if (wait == "2340") { break; } } Console.WriteLine("bot process started..."); Records.Clear(); Importable.Clear(); cases.Clear(); IWebDriver gc = new ChromeDriver(chromeOptions); Console.ForegroundColor = ConsoleColor.White; try { //...loging in gc.Navigate().GoToUrl("https://cwp.clientspace.net/Next/Login"); gc.FindElement(By.Name("LoginID")).SendKeys("lightbot"); gc.FindElement(By.Name("Password")).SendKeys("RPAuser!"); gc.FindElement(By.Name("Password")).SendKeys(Keys.Enter); //............. } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Login int to client space failed"); } //redireciting to reports one try { gc.Navigate().GoToUrl("https://cwp.clientspace.net/BusinessIntelligence/ReportViewer.aspx?rn=LightBot+Admins+Only\\AI1+Ancillary+Risk+Fees"); System.Threading.Thread.Sleep(4000); } catch { } //extracting data from report Al1 risk fee try { Console.WriteLine("Scrapping data :"); //getting reports from alteranating rows foreach (IWebElement c in gc.FindElements(By.ClassName("AlternatingItem"))) { Console.WriteLine("Data fount !"); ICollection <IWebElement> cols = c.FindElements(By.TagName("td")); Record r = new Record(cols.ElementAt(0).Text, cols.ElementAt(1).Text, cols.ElementAt(2).Text, cols.ElementAt(3).Text, cols.ElementAt(4).Text, cols.ElementAt(5).Text, cols.ElementAt(6).Text, cols.ElementAt(7).Text); Records.Add(r); } //getting records from normal rows foreach (IWebElement c in gc.FindElements(By.ClassName("ReportItem"))) { Console.WriteLine("Data fount !"); ICollection <IWebElement> cols = c.FindElements(By.TagName("td")); Record r = new Record(cols.ElementAt(0).Text, cols.ElementAt(1).Text, cols.ElementAt(2).Text, cols.ElementAt(3).Text, cols.ElementAt(4).Text, cols.ElementAt(5).Text, cols.ElementAt(6).Text, cols.ElementAt(7).Text); Records.Add(r); } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Data scrapping failed !"); Console.ForegroundColor = ConsoleColor.White; } //.......... //........... //moving to al2 report //redireciting to reports one try { gc.Navigate().GoToUrl("https://cwp.clientspace.net/BusinessIntelligence/ReportViewer.aspx?rn=LightBot+Admins+Only\\AI2+Ancillary+Risk+Fees"); System.Threading.Thread.Sleep(4000); } catch { } //extracting data from report Al1 risk fee try { Console.WriteLine("Scrapping data :"); //getting reports from alteranating rows foreach (IWebElement c in gc.FindElements(By.ClassName("AlternatingItem"))) { Console.WriteLine("Data fount !"); ICollection <IWebElement> cols = c.FindElements(By.TagName("td")); Record r = new Record(cols.ElementAt(0).Text, cols.ElementAt(1).Text, cols.ElementAt(2).Text, cols.ElementAt(3).Text, cols.ElementAt(4).Text, cols.ElementAt(5).Text, cols.ElementAt(6).Text, cols.ElementAt(7).Text); Records.Add(r); } //getting records from normal rows foreach (IWebElement c in gc.FindElements(By.ClassName("ReportItem"))) { Console.WriteLine("Data fount !"); ICollection <IWebElement> cols = c.FindElements(By.TagName("td")); Record r = new Record(cols.ElementAt(0).Text, cols.ElementAt(1).Text, cols.ElementAt(2).Text, cols.ElementAt(3).Text, cols.ElementAt(4).Text, cols.ElementAt(5).Text, cols.ElementAt(6).Text, cols.ElementAt(7).Text); Records.Add(r); } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Data scrapping from \"Al\" failed !"); Console.ForegroundColor = ConsoleColor.White; } Console.WriteLine("Data extracted from reports :\n"); foreach (Record r in Records) { if (r.location == null || r.location == "") { cases.Add(r); } else { Importable.Add(r); } r.printData(); } Console.WriteLine("\n Number of importable Records :" + Importable.Count); Console.WriteLine("\n Number of records for cases :" + cases.Count); if (cases.Count > 0) { foreach (Record record in cases) { Exception ex = new Exception(record.toString()); ErrorLogging2(ex); try { gc.Navigate().GoToUrl("https://cwp.clientspace.net/Next/peo/client"); gc.FindElement(By.Id("dropdownMenu1")).Click(); gc.FindElement(By.Id("All")).Click(); gc.FindElement(By.Name("ContractStage")).SendKeys(Keys.Backspace); gc.FindElement(By.Name("ContractStage")).SendKeys(Keys.Backspace); gc.FindElement(By.Name("ContractStage")).SendKeys(Keys.Backspace); gc.FindElement(By.Name("ContractStage")).SendKeys(Keys.Backspace); gc.FindElement(By.Name("ContractStage")).SendKeys(Keys.Backspace); gc.FindElement(By.Name("ContractStage")).SendKeys(Keys.Backspace); gc.FindElement(By.Name("ClientNumber")).SendKeys(record.clientId.ToString()); // put the client number here. System.Threading.Thread.Sleep(2000); gc.FindElement(By.ClassName("formSearchBtn")).Click(); System.Threading.Thread.Sleep(1000); gc.FindElements(By.ClassName("cs-underline"))[1].Click(); gc.FindElement(By.XPath("//*[@id='customHeaderHtml']/div[2]/div[6]/div/div[1]/table/tbody/tr/td[1]/span")).Click(); gc.FindElement(By.XPath("//*[@id='lstDataform_btnAdd']")).Click(); gc.FindElement(By.XPath("//*[@id='crCategory']")).SendKeys("R"); System.Threading.Thread.Sleep(1500); gc.FindElement(By.XPath("//*[@id='crCategory']")).SendKeys(Keys.Tab); gc.FindElement(By.XPath("//*[@id='fkCaseTypeID']")).SendKeys("M"); System.Threading.Thread.Sleep(1500); gc.FindElement(By.XPath("//*[@id='fkCaseTypeID']")).SendKeys(Keys.Enter); gc.FindElement(By.XPath("//*[@id='CallerName']")).SendKeys("Lightbot"); gc.FindElement(By.XPath("//*[@id='EmailAddress']")).SendKeys("*****@*****.**"); DateTime dateTime = DateTime.Now; var date = dateTime.ToString("MM/dd/yyyy"); gc.FindElement(By.XPath("//*[@id='DueDate']")).SendKeys(date); gc.FindElement(By.XPath("//*[@id='Subject']")).SendKeys(record.caseNo.ToString()); gc.FindElement(By.XPath("//*[@id='btnSave']")).Click(); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Result : Case creation Sucessfull."); } catch (Exception ex1) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Result : Case creation failed..!"); Exception e = new Exception("Case Reporting failed !"); ErrorLogging(ex1); ErrorLogging(e); } } } if (Importable.Count > 0) { //creating txt file for prism import string delimiter = "\t"; try { using (var writer = new System.IO.StreamWriter(basePath + "\\data.txt")) { foreach (Record i in Importable) { writer.WriteLine(i.billDate + delimiter + i.billEventCode + delimiter + i.billRates + delimiter + i.billUnits + delimiter + i.clientId + delimiter + delimiter + i.location + delimiter + delimiter + i.comment); } } } catch { Console.WriteLine("Import file creation failed."); } //moving to prism to try importing the text file. top: gc.Navigate().GoToUrl("https://ctw.prismhr.com/ctw/dbweb.asp?dbcgm=1"); System.Threading.Thread.Sleep(1000); //logging in prism try { gc.FindElement(By.XPath("//*[@id='text4v1']")).SendKeys("lightbot"); gc.FindElement(By.XPath("//*[@id='password6v1']")).SendKeys("RPAuser1!"); gc.FindElement(By.XPath("//*[@id='button8v1']")).Click(); System.Threading.Thread.Sleep(1000); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Prism login failed!"); Console.ForegroundColor = ConsoleColor.White; Exception e = new Exception("Prism Login failed !"); ErrorLogging(ex); ErrorLogging(e); } try { gc.FindElement(By.XPath("//*[@id='text31v1']")).Click(); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("C"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys(Keys.Backspace); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("c"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("l"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("i"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("e"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("n"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys("t"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys(" bill"); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys(Keys.Backspace); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys(Keys.Backspace); System.Threading.Thread.Sleep(1000); gc.FindElement(By.XPath("//*[@id='text31v1']")).SendKeys(Keys.Enter); System.Threading.Thread.Sleep(10000); } catch (Exception ex) { Exception e = new Exception("Client Bill Pending report opening failed !"); ErrorLogging(ex); ErrorLogging(e); goto end; } System.Threading.Thread.Sleep(1000); gc.FindElement(By.XPath("//*[@id='button31v2']")).Click(); System.Threading.Thread.Sleep(1000); String current = gc.CurrentWindowHandle; foreach (String winHandle in gc.WindowHandles) { gc.SwitchTo().Window(winHandle); } //sometimes the upload window doesn't open if (gc.CurrentWindowHandle != current) { try { gc.FindElement(By.XPath("//*[@id='fname']")).SendKeys(basePath + "\\data.txt"); //put the full path of file here gc.FindElement(By.XPath("//*[@id='submit1']")).Click(); System.Threading.Thread.Sleep(1000); gc.FindElement(By.XPath("//*[@id='BUTTON1']")).Click(); System.Threading.Thread.Sleep(20000); gc.SwitchTo().Window(current); } catch { try { gc.Close(); } catch { } try { gc.SwitchTo().Window(current); gc.Close(); } catch { } goto end; } try { Exception s = new Exception(gc.FindElement(By.XPath("//*[@id='body_span29v2']")).Text); ErrorLogging1(s); } catch { } try { gc.FindElement(By.XPath("//*[@id='button33v2']")).Click(); System.Threading.Thread.Sleep(2000); gc.FindElement(By.XPath("//*[@id='button32v2']")).Click(); System.Threading.Thread.Sleep(2000); gc.SwitchTo().Alert().Accept(); gc.SwitchTo().Window(current); gc.FindElement(By.XPath("//*[@id='button35v2']")).Click(); } catch (Exception e) { Console.WriteLine(e); gc.SwitchTo().Window(current); gc.FindElement(By.XPath("//*[@id='button35v2']")).Click(); } tryagain: try { gc.Close(); gc.Dispose(); Console.WriteLine("Process Complete..!"); } catch (Exception ex) { Exception e = new Exception("Chrome closing failed failed !"); ErrorLogging(ex); ErrorLogging(e); System.Threading.Thread.Sleep(10000); goto tryagain; } } else { tryagain: try { gc.Close(); gc.Dispose(); goto top; } catch (Exception ex) { Exception e = new Exception("Chrome closing failed failed !"); ErrorLogging(ex); ErrorLogging(e); System.Threading.Thread.Sleep(10000); goto tryagain; } } }//end of if condiditon end: Console.WriteLine("Process Completed..!"); Console.WriteLine("System going to wait in 3 sec..."); System.Threading.Thread.Sleep(3000); goto wait; }
/// <summary> /// /// </summary> public void Dispose() { Driver.Dispose(); }
static void Main(string[] args) { List <AccountInfo> taskAccount = new List <AccountInfo>(); string _account = string.Empty; string _passWord = string.Empty; string _companyID = "CTBC"; while (true) { Console.WriteLine("輸入帳號 不再新增輸入空白"); _account = Console.ReadLine(); if (string.IsNullOrEmpty(_account)) { break; } else { Console.WriteLine("輸入密碼"); _passWord = Console.ReadLine(); taskAccount.Add(new AccountInfo { Account = _account, Password = _passWord }); } } IWebDriver driver = new ChromeDriver(); string _url = @"https://www.leadercampus.com.tw/desktop/login";//URL Random crandom = new Random(); int classInt = 1150; int papers = crandom.Next(80, 100); string baseUrl = @"https://www.leadercampus.com.tw/desktop/course/"; taskAccount.ForEach(item => { if (!string.IsNullOrWhiteSpace(item.Account) && !string.IsNullOrWhiteSpace(item.Password)) { driver.Navigate().GoToUrl(_url); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); IWebElement btn = driver.FindElement(By.Id("agree_btn")); btn.Click(); IWebElement inputCompanyId = driver.FindElement(By.Name("company_account")); Thread.Sleep(500); inputCompanyId.Clear(); Thread.Sleep(500); inputCompanyId.SendKeys(_companyID); Thread.Sleep(500); IWebElement inputAcc = driver.FindElement(By.Name("account")); Thread.Sleep(500); inputAcc.Clear(); Thread.Sleep(500); inputAcc.SendKeys(item.Account); Thread.Sleep(500); IWebElement inputPassWrod = driver.FindElement(By.Name("password")); Thread.Sleep(500); inputPassWrod.Clear(); Thread.Sleep(500); inputPassWrod.SendKeys(item.Password); Thread.Sleep(500); IWebElement submitButton = driver.FindElement(By.ClassName("rbtn")); Thread.Sleep(2000); submitButton.Click(); Thread.Sleep(1300); if (classInt < papers) { classInt = 1150; } for (int i = 0; i <= papers; i++) { _url = $"{baseUrl}{classInt - i}"; driver.Navigate().GoToUrl(_url); Thread.Sleep(500); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10000); Thread.Sleep(crandom.Next(10000, 16000)); } } driver.Quit(); driver.Dispose(); driver = new ChromeDriver(); }); driver.Dispose(); Console.WriteLine("任務完成"); Console.ReadLine(); }
static void Main(string[] args) { Console.WriteLine("Entre com a sua agencia 4 digitos : "); var agencia = Console.ReadLine(); agencia = agencia.Length == 4 ? agencia : "SUA_AGENCIA_PARA_NAO_FICAR_DIGITANDO_E_APERTAR_ENTER"; Console.WriteLine("Entre com a sua conta com digito 6 digitos : "); var conta = Console.ReadLine(); conta = conta.Length == 6 ? conta : "LIKE_AGENCIA"; Console.WriteLine("Entre com a sua senha eletronica com digito 6 digitos : "); var senha = ""; senha = getSenha(senha); senha = senha.Length == 6 ? senha : "LIKE_AGENCIA"; Console.Clear(); var chromeOptions = new ChromeOptions(); chromeOptions.AddArguments("headless"); chromeOptions.AddArguments("window-size=1920,1080"); chromeOptions.AddArguments("start-maximized"); var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; IWebDriver driver = new ChromeDriver(chromeDriverService, chromeOptions); driver.Manage().Window.Maximize(); Console.WriteLine("Acessando site do Itau"); driver.Navigate().GoToUrl("https://www.itau.com.br/"); WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 2, 0)); try { wait.Until(ExpectedConditions.ElementIsVisible(By.Id("agencia"))); } catch (Exception) { Console.WriteLine("Nao foi possivel acessar o site : Enter para sair"); driver.Dispose(); Console.ReadLine(); Environment.Exit(0); } Console.WriteLine("Digitando Agencia e Conta"); driver.FindElement(By.Id("agencia")).SendKeys(agencia + conta); Thread.Sleep(1000); driver.FindElement(By.Id("btnLoginSubmit")).Click(); Console.WriteLine("Aguardando Carregar Teclado Virtual"); WebDriverWait wait2 = new WebDriverWait(driver, new TimeSpan(0, 2, 0)); try { wait2.Until(ExpectedConditions.ElementIsVisible(By.PartialLinkText(senha[0].ToString()))); } catch { Console.WriteLine("Impossivel achar o Teclado Virutal : Enter para sair"); driver.Dispose(); Console.ReadLine(); Environment.Exit(0); } Thread.Sleep(1000); Console.WriteLine("Digitando no Teclado Virtual"); foreach (var item in senha.ToCharArray()) { driver.FindElement(By.PartialLinkText(item.ToString())).Click(); } Console.WriteLine("Acessando Conta"); driver.FindElement(By.Id("acessar")).Click(); Console.WriteLine("Esperando Carregar Conta"); WebDriverWait wait3 = new WebDriverWait(driver, new TimeSpan(0, 2, 0)); try { wait3.Until(ExpectedConditions.ElementIsVisible(By.Id("saldo"))); } catch (Exception) { Console.WriteLine("Não Conseguimos ver o saldo : Enter para sair"); driver.Dispose(); Console.ReadLine(); Environment.Exit(0); } IJavaScriptExecutor js = (IJavaScriptExecutor)driver; js.ExecuteScript("popFechar()"); var saldoHTML = driver.FindElement(By.Id("saldo")).GetAttribute("innerHTML"); var primeiro = saldoHTML.IndexOf("<small>"); var ultimo = saldoHTML.LastIndexOf("</small>"); var substring = saldoHTML.Substring(primeiro, ultimo - primeiro).Replace("<small>", "").Replace("</small>", "").Replace("R$", "").Replace(@"\r", "").Replace(@"\n", "").Replace(@"\t", "").Trim(); double saldo = Double.Parse(substring); //ACESSA MENU //Actions builder = new Actions(driver); //IWebElement element = driver.FindElement(By.ClassName("ico-header-menu")); //builder.MoveToElement(element).Build().Perform(); //try //{ //} //catch (Exception e) //{ //} driver.FindElement(By.Id("accordionExibirBoxCartoes")).Click(); Thread.Sleep(2000); var cartHTML = driver.FindElement(By.Id("exibirBoxCartoes")).GetAttribute("innerHTML"); var primeirotable = cartHTML.IndexOf("<table"); var ultimotable = cartHTML.LastIndexOf("</table>"); var substringCartao = cartHTML.Substring(primeirotable, ultimotable - primeirotable + 9).Replace(@"\r", "").Replace(@"\n", "").Replace(@"\t", "").Replace("\r", "").Replace("\n", "").Replace("\t", "").Trim(); HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(substringCartao); var HTMLTableTRList = from table in doc.DocumentNode.SelectNodes("//table").Cast <HtmlNode>() from row in table.SelectNodes("//tr").Cast <HtmlNode>() from cell in row.SelectNodes("th|td").Cast <HtmlNode>() select new { Table_Name = table.Id, Cell_Text = cell.InnerText }; List <cartaoDTO> listaCartao = new List <cartaoDTO>(); int celula = 1; cartaoDTO cartao = new cartaoDTO(); foreach (var cell in HTMLTableTRList.Skip(4)) { var texto = Regex.Replace(cell.Cell_Text, @"\s+", " ").Trim(); if (celula == 1) { cartao = new cartaoDTO(); var posicaofinal = texto.IndexOf("final"); var posicaolimite = texto.IndexOf("Limite disponível"); cartao.Nome = texto.Substring(0, posicaofinal - 2).Trim(); cartao.Final = texto.Substring(posicaofinal + 5, posicaolimite - posicaofinal - 5).Trim(); var textoDisponivel = texto.Substring(posicaolimite + "Limite disponível".Length, texto.Length - posicaolimite - "Limite disponível".Length).Replace("R$", "").Replace(":", "").Trim(); cartao.Disponivel = Double.Parse(textoDisponivel); } if (celula == 2) { int dia = Int32.Parse(texto.Substring(0, 2)); int mes = Int32.Parse(texto.Substring(3, 2)); int ano = Int32.Parse(texto.Substring(6, 4)); cartao.dataVencimentoProxfatura = new DateTime(ano, mes, dia); } if (celula == 3) { cartao.FaturaAtual = Double.Parse(texto); } if (celula == 4) { cartao.Fechada = !texto.Equals("aberta"); listaCartao.Add(cartao); celula = 0; } celula++; } driver.Dispose(); Console.WriteLine("Seu saldo : " + saldo); Console.WriteLine("Seu(s) Cartões"); foreach (var item in listaCartao) { Console.WriteLine(item.ToString()); } string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + @"\Saldo.txt", true)) { file.WriteLine(saldo + " na data de : " + DateTime.Now); foreach (var item in listaCartao) { file.WriteLine(item.ToString() + " na data de : " + DateTime.Now); } } }
public void Dispose() { _driver?.Dispose(); }
public static void DisposeChomeDriver() { _chromeDriver.Dispose(); _chromeDriver = null; }
static void Main(string[] args) { GetKeyWordAmount(); string TargetEmail = GetEmail(); int intervalMinMainProgram = GetIntervalMinMain() * 1000; int intervalMaxMainProgram = GetIntervalMaxMain() * 1000; int intervalMinBetweenSearches = GetIntervalMinBetweenSearches() * 1000; int intervalMaxBetweenSearches = GetIntervalMaxBetweenSearches() * 1000; List <string> KeywordsUrl = new List <string>(); KeywordsUrl = SelectKeywordUrls(); List <string> xPaden = new List <string>(); xPaden = GetXpaden(); bool Running = true; while (Running) { foreach (string Keyword in KeywordsUrl) { Console.WriteLine("Zoekt nu naar: " + Keyword); IWebDriver driver = new ChromeDriver(); driver.Manage().Window.Maximize(); // Open chrome web driver driver.Navigate().GoToUrl(Keyword); DriverManager(driver); //IWebElement element = driver.FindElement(By.ClassName("site-search__controls__input")); // Switching to react modal driver.SwitchTo().ActiveElement(); try { IWebElement element1 = driver.FindElement(By.Id("user[first_name]")); element1.SendKeys(Keys.Escape); Console.WriteLine("Popup closed."); } catch (Exception) { Console.WriteLine("Waarschijnlijk geen popup."); } // Listings aantal ophalen. string listno = ""; int i = 0; while (xPaden.Count >= i) { if (listno == "") { string pad = xPaden[i]; try { listno = driver.FindElement(By.XPath(pad)).Text.ToString(); } catch { Console.WriteLine("Pad niet gevonden, volgende proberen."); } } i++; bool checkListno = listno.Contains("listing"); bool checkListno2 = listno.Contains("listings"); if (checkListno == true || checkListno2 == true) { i = 100; int listnoInt = TrimStringConvertToInt(listno); int aantalNieuweAdvertenties = CompareListingsWithDatabase(Keyword, listnoInt); if (aantalNieuweAdvertenties > 0) { string prijsAdvertentie = ""; try { prijsAdvertentie = driver.FindElement(By.XPath("/html/body/div[3]/section/div[2]/div/div/div/div[2]/div/div[2]/ul/li/div/a/div[2]/div/div/span")).Text.ToString(); Console.WriteLine("Prijs advertentie = " + prijsAdvertentie); } catch { SendErrorMail(5, "null"); } string knipsel1 = knipVoorsteHelftStringEnOmdraaien(Keyword); string knipsel2 = knipAchtersteHeftStringEnOmdraaien(knipsel1); string finalZoekwoord = knipsel2; finalZoekwoord = finalZoekwoord.Replace("%20", " "); SendEmail(TargetEmail, finalZoekwoord, Keyword, prijsAdvertentie, aantalNieuweAdvertenties); } } } driver.Dispose(); if (i != 100) { //Foutcode 2: xPad gebruikt door Reverb die wij niet afvangen. SendErrorMail(2, Keyword); } //driver.Dispose(); Console.WriteLine("Klaar met zoekURL: " + Keyword); Console.WriteLine("Resultaat: " + listno.ToString()); // Hier sleep BetweenSearches Random r = new Random(); int intervalBetweenSearches = r.Next(intervalMinBetweenSearches, intervalMaxBetweenSearches); Thread.Sleep(intervalBetweenSearches); Console.WriteLine(""); } // Foutcode 1: Programma loopt nog! SendErrorMail(1, "null"); // Hier sleep MainProgram Random r2 = new Random(); int intervalMainProgram = r2.Next(intervalMinMainProgram, intervalMaxMainProgram); Thread.Sleep(intervalMainProgram); } }
public void Dispose() { ChromeDriver.Dispose(); IsBrowserAberto = false; }
public void TearDown() { _driver.Dispose(); }
public void createPaymentTerminalGroup() { IWebDriver driver = new ChromeDriver(); HomePage home = new HomePage(driver); globals.expRpt.createTest("Create Payment Terminals Groups"); globals.expRpt.logReportStatement(AventStack.ExtentReports.Status.Pass, "Create Payment Terminals Groups"); globals.expRpt.flushReport(); EditCompanyPage editCompany = new EditCompanyPage(driver); CommonFunctions comFunc = new CommonFunctions(driver); ViewPaymentTerminalGroupPage paymentterminalgroup = new ViewPaymentTerminalGroupPage(driver); CreatePaymentTerminalGroupPage addPyamentTerminalGroup = new CreatePaymentTerminalGroupPage(driver); string fullpath = comFunc.getDatasourcePath(); using (StreamReader file = File.OpenText(fullpath)) using (JsonTextReader reader = new JsonTextReader(file)) { JObject data = (JObject)JToken.ReadFrom(reader); comFunc.loginToApplication(); // compare the loaded screen with the expected screen Assert.AreEqual("Company List", home.getText()); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); // search for the company.. update to "Company_Name" later paymentterminalgroup.enterCompanyName(data["setupCompany_Name2"].ToString()); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); editCompany.clickGo(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); paymentterminalgroup.clickVisittoEdit(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); Assert.AreEqual("QUESTAutoComp01", paymentterminalgroup.getcompanyDetailstoview()); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); paymentterminalgroup.clickPaymentTerminalsDropdown(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); paymentterminalgroup.clickPaymentTerminalGroups(); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); // compare the loaded screen with the expected screen Assert.AreEqual("Payment Terminal Groups", paymentterminalgroup.getPaymentTerminalGroupText()); driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30000); // click the add Payment terminal Group button addPyamentTerminalGroup.clickaddPyamentTerminalGroup(); // enter payment Terminal Group details globals.expRpt.logReportStatement(AventStack.ExtentReports.Status.Info, "Enter Comapny Details"); addPyamentTerminalGroup.setPaymentTerminalName(data["StoreName"].ToString()); addPyamentTerminalGroup.setdeliveryLine(data["pt_deliveryLine"].ToString()); addPyamentTerminalGroup.setSuburb(data["pt_postalSuburb"].ToString()); addPyamentTerminalGroup.setState(data["pt_state"].ToString()); addPyamentTerminalGroup.setpostalCode(data["pt_postalCode"].ToString()); addPyamentTerminalGroup.setCountry(data["pt_country"].ToString()); addPyamentTerminalGroup.setdeliveryAddresscheckbox(); addPyamentTerminalGroup.clickSavePaymentterminals(); } driver.Close(); driver.Quit(); driver.Dispose(); }
public void Dispose() { driver.Quit(); driver.Dispose(); }
public void ColdSendSmsToAllAds() { var urls = JsonConvert.DeserializeObject <KslUrls>(File.ReadAllText(kslJsonPath)); ChromeDriver chromeGv = null; var googleCreds = _settingsService.GetSettings <AppSettings>(settingsJsonPath).GoogleSettings; try { ///* chromeGv = new ChromeDriver { Url = "https://www.google.com/voice/b/0#inbox" }; Thread.Sleep(2000); if (DateTime.Now.Date > DateTime.Parse("2019-11-17")) { chromeGv.Manage().Window.Minimize(); } Thread.Sleep(5000); //login to GV chromeGv.FindElementById("identifierId").SendKeys(googleCreds.UserName); Thread.Sleep(2000); chromeGv.FindElementByCssSelector(".RveJvd").Click(); Thread.Sleep(5000); chromeGv.FindElementByName("password").SendKeys(googleCreds.Password); Thread.Sleep(2000); chromeGv.FindElementByCssSelector("#passwordNext .RveJvd").Click(); Thread.Sleep(5000); //*/ var processed = new List <string>(); ChromeDriver chromeKsl = null; foreach (var url in urls.pending) { try { string sellerName = null; string sellerPhone = null; string itemName = null; string itemPrice = null; ///* chromeKsl = new ChromeDriver { Url = url }; Thread.Sleep(2000); if (DateTime.Now.Date > DateTime.Parse("2019-11-17")) { chromeKsl.Manage().Window.Minimize(); } Thread.Sleep(5000); //fill data form KSL classifeds template try { sellerName = chromeKsl.FindElementByCssSelector("span.listingContactSeller-firstName-value") .Text; } catch (Exception ex) { } try { sellerPhone = chromeKsl.FindElementByCssSelector("span.listingContactSeller-optionText").Text .Replace("-", ""); } catch (Exception ex) { } try { itemName = chromeKsl.FindElementByCssSelector("h1.listingDetails-title").Text; } catch (Exception ex) { } try { itemPrice = chromeKsl.FindElementByCssSelector("h2.listingDetails-price").Text; } catch (Exception ex) { } //fill data form KSL cars template if (string.IsNullOrWhiteSpace(sellerName)) { try { sellerName = chromeKsl.FindElementByCssSelector("span.vdp-contact-text.first-name").Text; } catch (Exception ex) { } } if (string.IsNullOrWhiteSpace(sellerPhone)) { try { sellerPhone = new string(chromeKsl.FindElementByCssSelector("a.stupid-ios").Text .Where(Char.IsDigit).ToArray()); } catch (Exception ex) { } } if (string.IsNullOrWhiteSpace(itemName)) { try { itemName = chromeKsl.FindElementByCssSelector("h1.title").Text; } catch (Exception ex) { } } if (string.IsNullOrWhiteSpace(itemPrice)) { try { itemPrice = chromeKsl.FindElementByCssSelector("h3.price").Text; } catch (Exception ex) { } } if (!decimal.TryParse(sellerPhone, out _)) { continue; } //go to legacy GV //chromeGv.Url = "https://voice.google.com/"; //Thread.Sleep(2000); //chromeGv.FindElementByCssSelector(".gb_tc:nth-child(1) path").Click(); //Thread.Sleep(2000); //chromeGv.FindElementByCssSelector(".hide-xs .navList > div .navItemLabel").Click(); //Thread.Sleep(2000); //chromeGv.SwitchTo().Window(chromeGv.WindowHandles.Last()); //Thread.Sleep(2000); //go to new GV sms inbox chromeGv.Url = "https://voice.google.com/u/0/messages"; //click new text var newtextButton = chromeGv.FindElementByCssSelector(".gmat-subhead-2"); newtextButton.Click(); Thread.Sleep(2000); //newtextButton.SendKeys(sellerPhone); var phoneInput = chromeGv.FindElementByCssSelector(".mLSKFd"); phoneInput.Click(); Thread.Sleep(2000); phoneInput.SendKeys(sellerPhone); Thread.Sleep(2000); var message = $"Hi {sellerName}, I saw your KSL.com posting about {itemName.ToUpper()} for {itemPrice}. Link: {url} ; " + $"Please let me know if it is still available. Thank you for your time."; var messageInput = chromeGv.FindElementById("input_2"); messageInput.Click(); Thread.Sleep(2000); messageInput.SendKeys(message); Thread.Sleep(3000); var sendButton = chromeGv.FindElementByXPath("//div[@id=\'gc-quicksms-send2\']/div/div/div/div[2]"); sendButton.Click(); Thread.Sleep(2500); //*/ processed.Add(url); } catch (Exception ex) { Thread.Sleep(500); } finally { chromeKsl?.Close(); chromeKsl?.Dispose(); } } foreach (var url in processed) { urls.pending.Remove(url); urls.attempted.Add(url); } //save the empty list File.WriteAllText(kslJsonPath, JsonConvert.SerializeObject(urls)); } catch (Exception ex) { Thread.Sleep(500); } finally { chromeGv?.Close(); chromeGv?.Dispose(); } }
public void Dispose() { ChromeDriver.Dispose(); }
public void TearDown() { ChromeDriver?.Dispose(); }
public static void AfterScenario() { driver.Dispose(); }
public void Execute_Applier() { Logger.Log("---APLIER STARTED---"); // Initialize MongoDB driver var client = new MongoClient("mongodb://*****:*****@"Hi, I'd like to apply for the position of - {job.Title} I'm a highly experienced developer and available immediately. Jurij +447565111967"; try { driver.FindElementById("txtCov").Clear(); driver.FindElementById("txtCov").SendKeys(coveringLetter); } catch (Exception ex) { Logger.Log("Exception is generated - " + ex.Message); Logger.Log("Will Click on the button without filling the covering letter"); } } else { Logger.Log("Using web sites default coveringLetter."); } // Apply driver.FindElementById("btn1").Click(); // Move job from "jobs" to "jobs_applied" Applier.MoveJobToApplied(job, db); } // Close Chrome driver driver.Close(); // closing chrome browser driver.Dispose(); // killing chrome driver process Logger.Log("---APLIER ENDED---"); }
public void TearDown() { driver.Close(); driver.Dispose(); }
public void Dispose() { _chromeDriver?.Dispose(); }
static void Main(string[] args) { //Create reference of browser IWebDriver driver = new ChromeDriver(); //Create reference for interactions with browser Actions action = new Actions(driver); //Maximize browser window driver.Manage().Window.Maximize(); //To Delay execution for 02 sec. as to view the resize browser WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMinutes(1)); try { #region REGISTER //------------------Navigate to the Nopcommerce Registration Page------------------------------- driver.Navigate().GoToUrl("http://nop1.ysoftsolution.com/register"); Thread.Sleep(2000); //gender: By.Class = 'gender'; driver.FindElement(By.XPath("//input[@type='radio'][@name='Gender']")).Click(); Thread.Sleep(2000); //FirstName element IWebElement elementfirstName = driver.FindElement(By.Id("FirstName")); elementfirstName.SendKeys("Test First Name"); Thread.Sleep(2000); //LastName element IWebElement elementlastName = driver.FindElement(By.Id("LastName")); elementlastName.SendKeys("Test Last Name"); Thread.Sleep(2000); //Date of birth element var txtBirDay = driver.FindElement(By.Name("DateOfBirthDay")); action.ClickAndHold(txtBirDay).SendKeys("03").Perform(); Thread.Sleep(2000); var txtBirMonth = driver.FindElement(By.Name("DateOfBirthMonth")); action.ClickAndHold(txtBirMonth).SendKeys("March").Perform(); Thread.Sleep(2000); var txtBirYear = driver.FindElement(By.Name("DateOfBirthYear")); action.ClickAndHold(txtBirYear).SendKeys("2020").Perform(); Thread.Sleep(2000); //email element IWebElement elementEmail = driver.FindElement(By.Id("Email")); elementEmail.SendKeys("*****@*****.**"); Thread.Sleep(2000); //Comapny element IWebElement elementCompany = driver.FindElement(By.Id("Company")); elementCompany.SendKeys("TESTING COMPANY"); Thread.Sleep(2000); //NewsLetter element- uncheck as by Default : Checked driver.FindElement(By.Id("Newsletter")).Click(); Thread.Sleep(2000); //Password element IWebElement elementPassword = driver.FindElement(By.Id("Password")); elementPassword.SendKeys("test@123"); Thread.Sleep(2000); //ConfirmPassword element IWebElement elementConfirmPassword = driver.FindElement(By.Id("ConfirmPassword")); elementConfirmPassword.SendKeys("test@123"); Thread.Sleep(2000); //Click on Submit button : id 'register-button' driver.FindElement(By.Id("register-button")).Click(); //To Delay execution for 02 sec. as to view the resize browser wait = new WebDriverWait(driver, TimeSpan.FromMinutes(2)); Thread.Sleep(2000); //After successfully registered click on Continue button. driver.FindElement(By.Id("register-continue")).Click(); Thread.Sleep(2000); //Logout driver.FindElement(By.XPath("//a[text()='Log out']")).Click(); Thread.Sleep(2000); #endregion //-------------------------Navigate to the Nopcommerce LOGIN Page----------------------------- #region LOGIN //wait = new WebDriverWait(driver, TimeSpan.FromMinutes(2)); driver.Navigate().GoToUrl("http://nop1.ysoftsolution.com/login"); Thread.Sleep(2000); //LOGIN EMAIL driver.FindElement(By.XPath("//input[@type='email'][@name='Email']")).SendKeys("*****@*****.**"); Thread.Sleep(2000); //LOGIN Password driver.FindElement(By.XPath("//input[@type='password'][@name='Password']")).SendKeys("test@123"); Thread.Sleep(2000); //RememberMe driver.FindElement(By.XPath("//label[text()='Remember me?']")).Click(); Thread.Sleep(2000); //Login driver.FindElement(By.XPath("//input[@type='submit'][@value='Log in']")).Click(); Thread.Sleep(2000); #endregion //------------Forgot Password------------------ #region RECOVERY / Forgot Pasword //Navigate to Recovery Page driver.Navigate().GoToUrl("http://nop1.ysoftsolution.com/passwordrecovery"); Thread.Sleep(2000); //Email driver.FindElement(By.Id("Email")).SendKeys("*****@*****.**"); Thread.Sleep(2000); //Recover button driver.FindElement(By.XPath("//input[@type='submit'][@name='send-email']")).Click(); Thread.Sleep(2000); #endregion //----------Search------------- #region SEARCH PRODUCT //Navigate to home Page driver.Navigate().GoToUrl("http://nop1.ysoftsolution.com/"); Thread.Sleep(2000); //Search element with keyword searching -'Apple MacBook Pro 13-inch' driver.FindElement(By.XPath("//input[@type='text'][@name='q']")).SendKeys("Apple MacBook Pro 13-inch"); wait = new WebDriverWait(driver, TimeSpan.FromMinutes(2)); Thread.Sleep(2000); //Click on Search Button driver.FindElement(By.XPath("//text()[.='Search']/ancestor::a[1]")).Click(); Thread.Sleep(2000); //Click on searched Product driver.FindElement(By.XPath("//a[text()='Apple MacBook Pro 13-inch']")).Click(); //driver.Navigate().GoToUrl("http://nop1.ysoftsolution.com/apple-macbook-pro-13-inch"); Thread.Sleep(2000); //Product Images driver.FindElement(By.XPath("/html[1]/body[1]/div[6]/div[3]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[3]/img[1]")).Click(); Thread.Sleep(2000); driver.FindElement(By.XPath("/html[1]/body[1]/div[6]/div[3]/div[2]/div[1]/div[1]/div[1]/form[1]/div[1]/div[1]/div[1]/div[2]/div[2]/img[1]")).Click(); Thread.Sleep(2000); #endregion } catch (Exception ex) { Console.WriteLine(ex.StackTrace); } finally { driver.Dispose(); //Close the browser driver.Quit(); } }
public void Dispose() { Directory.Delete(_downloadDir, true); _driver?.Close(); _driver?.Dispose(); }
public List <Match> FetchMatches_SB() { ChromeDriver browser = new ChromeDriver(); List <Match> lsFootball = new List <Match>(); browser.Navigate().GoToUrl($"https://agentii.stanleybet.ro/sportsbetting/Fotbal/68"); Thread.Sleep(3000); IWebElement cookiewindow = browser.FindElement(By.CssSelector("[aria-labelledby='ui-dialog-title-cookieMessage']")); cookiewindow.FindElement(By.CssSelector("[class='ui-icon ui-icon-closethick']")).Click(); IWebElement window = browser.FindElement(By.CssSelector("[aria-labelledby='ui-dialog-title-age18Message']")); window.FindElement(By.CssSelector("[class='successButton ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only']")).Click(); IWebElement games = browser.FindElement(By.CssSelector("[class='oddsTable drop-shadow lifted']")); ICollection <IWebElement> odds = games.FindElements(By.ClassName("trOdd")); ICollection <IWebElement> evens = games.FindElements(By.ClassName("trEven")); foreach (var item in odds) { lsFootball.Add(new Match()); string teams = item.FindElement(By.CssSelector("[class='alignLeft fullWidth']")).GetAttribute("textContent"); ICollection <IWebElement> tds = item.FindElements(By.TagName("td")); int iterator = 0; string home = teams.Substring(0, teams.Length - teams.IndexOf("-") - 3); string away = teams.Substring(teams.IndexOf("-") + 2); lsFootball.Last().HomeTeam = home; lsFootball.Last().AwayTeam = away; lsFootball.Last().Bets = new Dictionary <string, double>(); foreach (var td in tds) { if (iterator == 1) //hour { lsFootball.Last().PlayingDate = DateTime.ParseExact(td.GetAttribute("textContent"), "HH:mm", null); } if (iterator == 2) //date { if (lsFootball.Last().PlayingDate.Hour != DateTime.Now.Hour) { lsFootball.Last().PlayingDate.AddDays(1); } } if (iterator == 5) //1 { string cota = td.GetAttribute("textContent"); if (cota == "-") { break; } if (cota.Contains(",")) { cota.Replace(",", "."); } lsFootball.Last().Bets.Add("1", Double.Parse(cota)); } if (iterator == 6) //X { string cota = td.GetAttribute("textContent"); if (cota == "-") { break; } if (cota.Contains(",")) { cota.Replace(",", "."); } lsFootball.Last().Bets.Add("X", Double.Parse(cota)); } if (iterator == 7) //2 { string cota = td.GetAttribute("textContent"); if (cota == "-") { break; } if (cota.Contains(",")) { cota.Replace(",", "."); } lsFootball.Last().Bets.Add("2", Double.Parse(cota)); } iterator++; } } foreach (var item in evens) { lsFootball.Add(new Match()); string teams = item.FindElement(By.CssSelector("[class='alignLeft fullWidth']")).GetAttribute("textContent"); ICollection <IWebElement> tds = item.FindElements(By.TagName("td")); int iterator = 0; string home = teams.Substring(0, teams.Length - teams.IndexOf("-") - 3); string away = teams.Substring(teams.IndexOf("-") + 2); lsFootball.Last().HomeTeam = home; lsFootball.Last().AwayTeam = away; lsFootball.Last().Bets = new Dictionary <string, double>(); foreach (var td in tds) { if (iterator == 1) //hour { lsFootball.Last().PlayingDate = DateTime.ParseExact(td.GetAttribute("textContent"), "HH:mm", null); } if (iterator == 2) //date { if (lsFootball.Last().PlayingDate.Hour != DateTime.Now.Hour) { lsFootball.Last().PlayingDate.AddDays(1); } } if (iterator == 5) //1 { string cota = td.GetAttribute("textContent"); if (cota == "-") { break; } if (cota.Contains(",")) { cota.Replace(",", "."); } lsFootball.Last().Bets.Add("1", Double.Parse(cota)); } if (iterator == 6) //X { string cota = td.GetAttribute("textContent"); if (cota == "-") { break; } if (cota.Contains(",")) { cota.Replace(",", "."); } lsFootball.Last().Bets.Add("X", Double.Parse(cota)); } if (iterator == 7) //2 { string cota = td.GetAttribute("textContent"); if (cota == "-") { break; } if (cota.Contains(",")) { cota.Replace(",", "."); } lsFootball.Last().Bets.Add("2", Double.Parse(cota)); } iterator++; } } browser.Dispose(); return(lsFootball); }