public static void PlaceBet(string envo) { OpenRefresh("https://www.parimatch.com"); OpenTab($"https://www.parimatch.com/bet.html?ARDisabled=on&hl={envo}"); var f1 = driver?.FindElementById("f1").GetAttribute("innerHTML"); var internalId = f1.GetCssNode("div.container > a").Attributes["name"].Value; var headers = f1.GetCssNode($"table#g{internalId} > tbody"); var main = f1.GetCssNode($"table#g{internalId} > tbody.row1"); var props = f1.GetCssNode($"table#g{internalId} > tbody.row1.props"); var originBetId = main.InnerHtml.GetCssNode("a").Attributes["id"].Value; var betId = originBetId.Split('_').Last(); OpenTab($"https://www.parimatch.com/stake.html?ev={betId}&bm=2"); driver.FindElementByName("sums").SendKeys("3"); driver.FindElementById("do_stake").Click(); }
public LogInPage(ChromeDriver driver) { signInBtn = driver.FindElementById("skip_userNav"); this.driver = driver; }
static void Main(string[] args) { ChromeDriver chromeDriver = new ChromeDriver(); chromeDriver.Navigate().GoToUrl(link); try { for (int i = 0; i < 15; i++) { try { chromeDriver.ExecuteScript("scroll(0, 125000);"); var more = chromeDriver.FindElementById("show_more_results"); more.Click(); Thread.Sleep(300); } catch (Exception) { throw; } } } catch (Exception) { } HtmlDocument document = new HtmlDocument(); document.LoadHtml(chromeDriver.PageSource); var linksNode = document.DocumentNode.SelectNodes(".//a[@class='vendor-card__image js-vendor-card__image']"); var links = linksNode.Select(x => x.GetAttributeValue("href", "")); var listModel = new List <Model>(); foreach (var linkItem in links) { chromeDriver.Navigate().GoToUrl($"https://www.gigsalad.com/{linkItem}"); HtmlDocument documentItem = new HtmlDocument(); documentItem.LoadHtml(chromeDriver.PageSource); var model = new Model(); var userName = documentItem.DocumentNode.SelectSingleNode(".//h1[@class='profile-vendor-card__act-name']").InnerText; var category = documentItem.DocumentNode.SelectSingleNode(".//a[@class='link--secondary-color']").InnerText; var informationDivs = documentItem.DocumentNode.SelectSingleNode(".//div[@class='row small-up-1 medium-up-2']"); if (informationDivs != null) { var number = informationDivs.ChildNodes.FirstOrDefault(x => x.InnerText.Contains("Call")); var phoneNumber = number?.SelectSingleNode(".//a[@data-drop-type='profileShowPhone']").GetAttributeValue("data-promokit-phone", ""); if (!string.IsNullOrEmpty(phoneNumber)) { model.Phone = phoneNumber; } var website = informationDivs?.ChildNodes?.FirstOrDefault(x => x.InnerText.Contains("Website"))?.SelectSingleNode(".//a")?.GetAttributeValue("href", ""); if (!string.IsNullOrEmpty(website)) { model.WebSite = website; } } var socialDiv = documentItem.DocumentNode.SelectSingleNode(".//div[@id='social']"); if (socialDiv != null) { var linksSoc = socialDiv.SelectNodes(".//a").Select(x => x.GetAttributeValue("href", "")); if (linksSoc != null && linksSoc.Count() != 0) { model.SocialLink = string.Join(" , ", linksSoc); } } model.Email = EmailRegex(chromeDriver.PageSource); model.UserName = userName; model.Category = category; listModel.Add(model); } WriteCSV(listModel, "E:\\Djs.csv"); }
public string Cambium(ChromeDriver browser) { BrowserExt ElementCheck = new BrowserExt(); //Browser should be looking at ATA page by now string ATAInfo = ""; browser.FindElementById("user_name").SendKeys(userName); browser.FindElementById("password").SendKeys(passWord); if (ElementCheck.IsElemenentPresent(By.Id("login"), browser) == true) { browser.FindElementById("login").Click(); //loginBtn.Click(); } else { //If login button is not present we'll create it ourselves same way DOM originally does it. ((IJavaScriptExecutor)browser).ExecuteScript("document.write('<input id='login' type='submit' onclick='OnSubmit(this.form);');"); browser.FindElementById("login").Click(); } //Get phone lines and their status, format and add to ATAInfo string. try { var line1 = browser.FindElementById("sipStatus_1").Text; var line1_hook = browser.FindElementById("hookStatus_1").Text; var line1_Status = browser.FindElementById("useStatus_1").Text; var line2 = browser.FindElementById("sipStatus_2").Text; var line2_hook = browser.FindElementById("hookStatus_2").Text; var line2_Status = browser.FindElementById("useStatus_2").Text; ATAInfo = $"Phone lines in ATA:\nline 1 is {line1} and is {line1_hook} hook and currently {line1_Status}\n"; ATAInfo += $"line 2 is {line2} and is {line2_hook} hook and currently {line2_Status}\n"; //Find DHCP table var LAN_HostBtn = browser.FindElementById("menuSubList"); LAN_HostBtn.FindElements(By.TagName("li"))[1].Click(); } catch (Exception e) { Console.WriteLine($"Error on ATA homepage, ref: {e.ToString()}"); return(ATAInfo = "Couldn't get into ATA"); } //Gather DHCP table info.. try { var DHCP_Table = browser.FindElementById("PageList"); DHCP_Table = DHCP_Table.FindElement(By.TagName("table")); var DHCP_Rows = DHCP_Table.FindElements(By.TagName("tr")); var DHCP_Count = DHCP_Rows.Count; string DHCP_Info = $"{DHCP_Count.ToString()} Devices were found in DHCP Table:\n"; int counter = 1; //Iterate over each row, grab all DHCP items listed there foreach (var Row in DHCP_Rows) { var info = Row.FindElements(By.TagName("td")); /*Should be 7 items per Entry in DHCP table * 0 - MAC address * 1 - LAN IP * 2 - Interface Type * 3 - Address Source * 4 - Expires in * 5 - Device Name * 6 - DHCP Status */ DHCP_Info += $"DCHP Item# {counter.ToString()} MAC: {info[0].Text} IP: {info[1].Text} Host Name: {info[5].Text} DHCP Status: {info[6].Text}\n"; counter++; } ATAInfo += DHCP_Info; } catch (NotFoundException NoDCHP) { Console.WriteLine($"Nothing found in DHCP Table {NoDCHP.ToString()}"); ATAInfo += "Nothing found in DHCP Table"; //throw; } catch (Exception e) { Console.WriteLine($"Some other DHCP error occured... {e.ToString()}"); ATAInfo += "Nothing found in DHCP table"; } //Should be all done with ATA, go ahead and reboot dat hoe! browser.FindElementById("loginReboot").Click(); //Combine information ATAInfo += "Rebooted / Rebuilt ATA"; try { var handleAlert = browser.SwitchTo().Alert(); handleAlert.Accept(); } catch (Exception e) { Console.WriteLine("Couldn't handle Alert, was not able to reboot ATA"); Console.WriteLine(e.StackTrace); } return(ATAInfo); }
public void Login() { //login var username = "******"; var password = "******"; _chrome.Navigate().GoToUrl("http://localhost:5000/Authentication/Login"); _chrome.FindElementById("Username").SendKeys(username); _chrome.FindElementById("Password").SendKeys(password); _chrome.FindElementById("Login").Click(); Assert.Contains(username, _chrome.FindElementById("DashboardMsg").Text); _chrome.Close(); }
private const int NUMBER_OF_RELOADS = 2; // Update the number of reloads to be done with this card static void Main(string[] args) { var last4CardDigits = CARD_NUMBER.Substring(CARD_NUMBER.Length - 4); string reloadUrl = "https://smile.amazon.com/asv/reload/"; // now automate using Selenium var driver = new ChromeDriver(); var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); // Sign in driver.Navigate().GoToUrl(reloadUrl); driver.FindElementById("form-submit-button").Click(); wait.Until(d => d.Title == "Amazon Sign In"); driver.FindElementById("ap_email").SendKeys(AMAZON_USERNAME); //driver.FindElementById("ap_signin_existing_radio").Click(); driver.FindElementById("ap_password").SendKeys(AMAZON_PASSWORD); driver.FindElementById("signInSubmit").Click(); Console.WriteLine("Signed in successfully! Optionally waiting for 60 seconds for allowing to allow user input for 2FA"); // The following is to accomodate manual input for 2FA wait.Timeout = TimeSpan.FromMinutes(1); wait.Until(d => d.Title == "Reload Your Balance"); wait.Timeout = TimeSpan.FromSeconds(10); // Loop and buy gift cards for (int i = 0; i < NUMBER_OF_RELOADS; i++) { Console.WriteLine($"Iteration {i} ------ "); if (driver.Title != "Reload Your Balance") { driver.Navigate().GoToUrl(reloadUrl); } wait.Until(d => d.Title == "Reload Your Balance"); driver.FindElementById("asv-manual-reload-amount").SendKeys(GIFT_CARD_AMOUNT.ToString()); Thread.Sleep(100); driver.FindElementByXPath($"//span[contains(text(), '{CARD_TYPE}')]").Click(); //driver.FindElementByName("pmts-credit-card-row")[2].click() Thread.Sleep(100); if (i == 0) { bool retry = false; try { driver.FindElementByXPath($"//input[@placeholder='ending in {last4CardDigits}']").SendKeys(CARD_NUMBER); } catch (Exception) { driver.FindElementById("form-submit-button").Click(); retry = true; } if (retry) { Thread.Sleep(3000); driver.FindElementByXPath($"//input[@placeholder='ending in {last4CardDigits}']").SendKeys(CARD_NUMBER); } Thread.Sleep(100); var elements = driver.FindElementsByXPath("//button[contains(.,'Confirm Card')]"); elements.First(x => x.Displayed).Click(); Thread.Sleep(100); } driver.FindElementById("form-submit-button").Click(); Thread.Sleep(3000); try { driver.FindElementByXPath("//span[contains(.,'this message again')]").Click(); Thread.Sleep(100); driver.FindElementById("asv-reminder-action-primary").Click(); Thread.Sleep(100); } catch (NoSuchElementException) { // do nothing } driver.Navigate().GoToUrl(reloadUrl); } driver.Quit(); Console.Write("Done!!"); }
private void UpdatePageId(string pageId = null) { this.pageId = pageId ?? driver.FindElementById("__PageIdField").GetAttribute("value"); }
public void ChromeTest() { using (var WebDriver = new ChromeDriver()) { WebDriver.Manage().Window.Maximize(); WebDriver.Navigate().GoToUrl(baseURL); var firstName = WebDriver.FindElementById("RESULT_TextField-2"); firstName.SendKeys("Marco"); var lastName = WebDriver.FindElementById("RESULT_TextField-3"); lastName.SendKeys("Serrano"); var address = WebDriver.FindElementById("RESULT_TextField-4"); address.SendKeys("123 Street St."); var address2 = WebDriver.FindElementById("RESULT_TextField-5"); address2.SendKeys("Apt 123"); var city = WebDriver.FindElementById("RESULT_TextField-6"); city.SendKeys("Townsville"); var state = WebDriver.FindElementById("RESULT_RadioButton-7"); var selectElement = new OpenQA.Selenium.Support.UI.SelectElement(state); selectElement.SelectByText("Texas"); var zipCode = WebDriver.FindElementById("RESULT_TextField-8"); zipCode.SendKeys("77777"); var phone = WebDriver.FindElementById("RESULT_TextField-9"); phone.SendKeys("5557771234"); var email = WebDriver.FindElementById("RESULT_TextField-10"); email.SendKeys("*****@*****.**"); OpenQA.Selenium.Interactions.Actions actions = new Actions(WebDriver); actions.MoveToElement(email); actions.Perform(); var membership = WebDriver.FindElementByXPath("//div[@id='q16']/table/tbody/tr/td/label"); membership.Click(); membership = WebDriver.FindElementByXPath("//div[@id='q16']/table/tbody/tr/td[1]/label"); membership.Click(); membership = WebDriver.FindElementByXPath("//div[@id='q16']/table/tbody/tr/td[2]/label"); membership.Click(); var contact = WebDriver.FindElementByXPath("//div[@id='q21']/table/tbody/tr/td/label"); contact.Click(); contact = WebDriver.FindElementByXPath("//div[@id='q21']/table/tbody/tr/td[2]/label"); contact.Click(); contact = WebDriver.FindElementByXPath("//div[@id='q21']/table/tbody/tr/td[3]/label"); //contact.Click(); contact.Click(); var terms = WebDriver.FindElementByXPath("//div[@id='q30']/table/tbody/tr/td/label"); terms.Click(); var submit = WebDriver.FindElementById("FSsubmit"); submit.Submit(); Thread.Sleep(5000); WebDriver.Close(); } }
public void TestForAdmin() { using (var driver = new ChromeDriver()) { //open register page driver.Navigate().GoToUrl("http://localhost:4200/home"); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); var pageTitle = driver.PageSource.Contains("ABC Healthcare"); Assert.IsTrue(pageTitle); var LogIn = driver.FindElementByXPath("/html/body/app-root/app-nav-bar/nav/div/ul/div[1]/li/a"); Assert.IsNotNull(LogIn); LogIn.Click(); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); pageTitle = driver.PageSource.Contains("Sign In"); Assert.IsTrue(pageTitle); driver.FindElementByName("UserName").SendKeys("Admin"); driver.FindElementByName("Password").SendKeys("1234"); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); var SignIn = driver.FindElementById("signin"); Assert.IsNotNull(SignIn); SignIn.Click(); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); pageTitle = driver.PageSource.Contains("Filters"); Assert.IsTrue(pageTitle); var AdminPanel = driver.FindElementByXPath("/html/body/app-root/app-nav-bar/nav/div[1]/ul/div[2]/li/a"); Assert.IsNotNull(AdminPanel); AdminPanel.Click(); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); pageTitle = driver.PageSource.Contains("Product Detail Register"); Assert.IsTrue(pageTitle); driver.FindElementByName("productName").SendKeys("test"); driver.FindElementByName("imageUrl").SendKeys("http:test/pic.com"); driver.FindElementByName("price").SendKeys("30"); driver.FindElementByName("description").SendKeys("this is a test"); driver.FindElementByName("productType").SendKeys("Tablet"); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); var Submit = driver.FindElementByXPath("/html/body/app-root/app-admin-panel/div/div/div/div[1]/app-admin-detail/form/div[6]/button"); Assert.IsNotNull(Submit); Submit.Click(); new WebDriverWait(driver, TimeSpan.FromMinutes(3)).Until( d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete") ); var Logout = driver.FindElementByXPath("/html/body/app-root/app-nav-bar/nav/div[3]/button"); Assert.IsNotNull(Logout); Logout.Click(); } }
static string regionStr = "12"; // małopolska static void Main(string[] args) { //ParseStrings(); string dir = Directory.GetCurrentDirectory(); if (!File.Exists(Path.Combine(dir, "chromedriver.exe"))) { dir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "6obcy"); } SoundPlayer alert = new SoundPlayer("alert.wav"); SoundPlayer error = new SoundPlayer("error.wav"); using (ChromeDriver driver = new ChromeDriver(dir)) { //driver.Navigate("https://6obcy.org"); driver.Url = "https://6obcy.org"; driver.Navigate(); var stateButton = driver.FindElementById("intro-interface-location-button"); stateButton.Click(); LoadConfig(dir); var malopolska = driver.FindElementByClassName("location-id-" + regionStr); malopolska.Click(); var startbutton = driver.FindElementById("intro-start"); startbutton.Click(); Thread.Sleep(1000); var textInput = driver.FindElementById("box-interface-input"); var chatBox = driver.FindElementById("log-dynamic"); var welcomeMessage = driver.FindElementById("log-begin"); while (true) { try { string style = welcomeMessage.GetAttribute("style"); while (style.Contains("none")) { Console.WriteLine("Waiting for someone..."); style = welcomeMessage.GetAttribute("style"); Thread.Sleep(500); } var startTime = DateTime.Now; for (int i = 0; ; i++) { if (i > 0) { var messages = chatBox.FindElements(By.ClassName("log-msg")); if (messages.Count != 0) { string msg = chatBox.FindElements(By.ClassName("log-msg")).LastOrDefault().Text; if (!msg.ToLower().Contains("k") && msg.ToLower().Contains("m")) { while ((DateTime.Now - startTime).Seconds < 5) { Thread.Sleep(250); } Disconnect(driver); error.Play(); break; } if (msg.ToLower().Contains("km")) { textInput.SendKeys("M\n"); } else { alert.Play(); while (true) { var disconnectMessage = driver.FindElementByClassName("log-disconnected"); style = disconnectMessage.GetAttribute("style"); if (style.Contains("block")) { Disconnect(driver, false); break; } Thread.Sleep(1000); } break; } } } else { textInput.SendKeys("Hej, M19 Km?\n"); } int count = chatBox.FindElements(By.ClassName("log-msg")).Count; bool disconnected = false; while (count == chatBox.FindElements(By.ClassName("log-msg")).Count) { if ((DateTime.Now - startTime).Seconds > 10 && driver.FindElement(By.Id("log-stranger-typing")).GetAttribute("style") == "display: none;") { Disconnect(driver); disconnected = true; break; } var disconnectMessage = driver.FindElementByClassName("log-disconnected"); style = disconnectMessage.GetAttribute("style"); if (style.Contains("block")) { Disconnect(driver, false); disconnected = true; break; } Thread.Sleep(500); //Console.WriteLine("Count: " + count.ToString()); } if (disconnected) { break; } } } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.ToString()); Console.ResetColor(); } } Console.WriteLine("Waiting for keypress..."); Console.ReadKey(); } }
static void Main(string[] args) { var options = new ChromeOptions(); //options.AddArgument("--headless"); options.AddArguments("--disable-gpu"); options.AddArguments("disable-popup-blocking");//to disable pop-up blocking var chromeDriver = new ChromeDriver(options); chromeDriver.Navigate().GoToUrl("https://login.yahoo.com/"); Console.WriteLine("In Yahoo home page"); chromeDriver.Manage().Window.Maximize(); chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); chromeDriver.FindElementById("login-username").SendKeys("*****@*****.**"); chromeDriver.FindElementById("login-signin").Click(); chromeDriver.FindElementById("login-passwd").SendKeys("@nuk1978"); chromeDriver.FindElementById("login-signin").Click(); chromeDriver.Url = "https://finance.yahoo.com/portfolio/p_1/view/v1"; Console.WriteLine("In yahoo finance page"); /* * * var closePopup = chromeDriver.FindElementByXPath("//dialog[@id = '__dialog']/section/button"); * closePopup.Click(); * var items = chromeDriver.FindElementsByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[*]/td[*]"); * * foreach(var item in items) * { * Console.WriteLine("My WatchList: " + item.Text); * } */ //var closePopup = chromeDriver.FindElementByXPath("//*[@id=\"fin - tradeit\"]/div[2]/div"); var closePopup = chromeDriver.FindElementByXPath("//dialog[@id = '__dialog']/section/button"); closePopup.Click(); //var items = chromeDriver.FindElementsByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[*]/td[*]/span/a").GetAttribute; IWebElement list = chromeDriver.FindElementByTagName("tbody"); System.Collections.ObjectModel.ReadOnlyCollection <IWebElement> items = list.FindElements(By.TagName("tr")); int count = items.Count(); List <Stock> result = new List <Stock>(); Console.WriteLine(count); //loop to get details of each stock symbol for (int i = 1; i <= count; i++) { Console.WriteLine(i); var symbol = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[1]/span/a").GetAttribute("innerText"); var lastprice = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[2]/span").GetAttribute("innerText"); var change = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[3]/span").GetAttribute("innerText"); var percentChange = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[4]/span").GetAttribute("innerText"); var currency = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[5]").GetAttribute("innerText"); var avgVolume = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[9]").GetAttribute("innerText"); var marketCap = chromeDriver.FindElementByXPath("//*[@id=\"main\"]/section/section[2]/div[2]/table/tbody/tr[" + i + "]/td[13]/span").GetAttribute("innerText"); Stock stock = new Stock(); Console.WriteLine(symbol); stock.Symbol = symbol; Console.WriteLine(lastprice); stock.Price = Decimal.Parse(lastprice); Console.WriteLine(change); stock.Change = Decimal.Parse(change); Console.WriteLine(percentChange); stock.PercentChange = Decimal.Parse(percentChange.Trim('%')); Console.WriteLine(currency); stock.Currency = currency; Console.WriteLine(avgVolume); stock.AverageVolume = avgVolume; Console.WriteLine(marketCap); stock.MarketCap = marketCap; //result.Add(stock); //chromeDriver.Close(); } }
public void DownloadTestSets() { using (var driver = new ChromeDriver()) { driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(websiteLink); System.Threading.Thread.Sleep(2000); //Click the google map marker driver.FindElementByCssSelector("div[title='thor']").Click(); System.Threading.Thread.Sleep(2000); //Click the View Details driver.FindElementByCssSelector("button[onclick^=DisplayStationDataTable]").Click(); //Click the result range System.Threading.Thread.Sleep(2000); //Click the results driver.FindElementById("resultrange").Click(); System.Threading.Thread.Sleep(2000); //Click the all time filter driver.FindElementByCssSelector("li[data-range-key=\"All Time\"]").Click(); System.Threading.Thread.Sleep(2000); //Gather all the elements that are are in the results table var test = driver.FindElementsByCssSelector("table[id=resultsTable] tbody > tr"); //ensure 2 data sets are gotten Assert.AreEqual(2, test.Count, "Wrong number of data sets returned"); //These are our expected values for this specific test set Assert.AreEqual("1/3/2018, 11:00:00 PM 14.4 24.1 Southeast 3.491153 0.000000 2.880000 --- ---", test[0].Text, "Incorrect values return for first data set"); Assert.AreEqual("1/3/2018, 5:00:00 PM 10.5 15 West 51.862736 0.000000 0.000000 --- ---", test[1].Text, "Incorrect values return for second data set"); } using (var driver = new FirefoxDriver()) { driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(websiteLink); System.Threading.Thread.Sleep(2000); //Click the google map marker driver.FindElementByCssSelector("div[title='thor']").Click(); System.Threading.Thread.Sleep(2000); //Click the View Details driver.FindElementByCssSelector("button[onclick^=DisplayStationDataTable]").Click(); //Click the result range System.Threading.Thread.Sleep(2000); //Click the results driver.FindElementById("resultrange").Click(); System.Threading.Thread.Sleep(2000); //Click the all time filter driver.FindElementByCssSelector("li[data-range-key=\"All Time\"]").Click(); System.Threading.Thread.Sleep(2000); //Gather all the elements that are are in the results table var test = driver.FindElementsByCssSelector("table[id=resultsTable] tbody > tr"); System.Threading.Thread.Sleep(2000); //ensure 2 data sets are gotten Assert.AreEqual(2, test.Count, "Wrong number of data sets returned"); //These are our expected values for this specific test set Assert.AreEqual("1/3/2018, 11:00:00 PM 14.4 24.1 Southeast 3.491153 0.000000 2.880000 --- ---", test[0].Text, "Incorrect values return for first data set"); Assert.AreEqual("1/3/2018, 5:00:00 PM 10.5 15 West 51.862736 0.000000 0.000000 --- ---", test[1].Text, "Incorrect values return for second data set"); } }
public void DownloadSpecificRangeFailure() { using (var driver = new ChromeDriver()) { driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(websiteLink); System.Threading.Thread.Sleep(2000); //Click the google map marker driver.FindElementByCssSelector("div[title='thor']").Click(); System.Threading.Thread.Sleep(2000); System.Threading.Thread.Sleep(2000); //Click the View Details driver.FindElementByCssSelector("button[onclick^=DisplayStationDataTable]").Click(); //Click the result range System.Threading.Thread.Sleep(2000); //Click the results driver.FindElementById("resultrange").Click(); System.Threading.Thread.Sleep(2000);; //Select a valid range driver.FindElementByCssSelector("li[data-range-key=\"Custom Range\"]").Click(); driver.FindElementByCssSelector("input[name=daterangepicker_start]").Clear(); driver.FindElementByCssSelector("input[name=daterangepicker_start]").SendKeys(@"01/04/2018"); driver.FindElementByCssSelector("input[name=daterangepicker_end]").Clear(); driver.FindElementByCssSelector("input[name=daterangepicker_end]").SendKeys(@"01/04/2018"); driver.FindElementByCssSelector("button[class^=applyBtn").Click(); System.Threading.Thread.Sleep(2000); //Gather all the elements that are are in the results table var test = driver.FindElementsByCssSelector("table[id=resultsTable] tbody > tr"); //ensure 2 data sets are gotten Assert.AreEqual(0, test.Count, "Wrong number of data sets returned"); } using (var driver = new FirefoxDriver()) { driver.Manage().Window.Maximize(); driver.Navigate().GoToUrl(websiteLink); System.Threading.Thread.Sleep(2000); //Click the google map marker driver.FindElementByCssSelector("div[title='thor']").Click(); System.Threading.Thread.Sleep(2000); //Click the View Details driver.FindElementByCssSelector("button[onclick^=DisplayStationDataTable]").Click(); //Click the result range System.Threading.Thread.Sleep(2000); //Click the results driver.FindElementById("resultrange").Click(); System.Threading.Thread.Sleep(2000);; //Select a valid range driver.FindElementByCssSelector("li[data-range-key=\"Custom Range\"]").Click(); driver.FindElementByCssSelector("input[name=daterangepicker_start]").Clear(); driver.FindElementByCssSelector("input[name=daterangepicker_start]").SendKeys(@"01/04/2018"); driver.FindElementByCssSelector("input[name=daterangepicker_end]").Clear(); driver.FindElementByCssSelector("input[name=daterangepicker_end]").SendKeys(@"01/04/2018"); driver.FindElementByCssSelector("button[class^=applyBtn").Click(); System.Threading.Thread.Sleep(2000); //Gather all the elements that are are in the results table var test = driver.FindElementsByCssSelector("table[id=resultsTable] tbody > tr"); //ensure 2 data sets are gotten Assert.AreEqual(0, test.Count, "Wrong number of data sets returned"); } }
private void BwStart_DoWork(object sender, DoWorkEventArgs e) { if (BwStart.CancellationPending) { e.Cancel = true; return; } IJavaScriptExecutor js = (IJavaScriptExecutor)driver; driver.Navigate().GoToUrl(TeURL.Text); Thread.Sleep(5000); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); var view = driver.FindElementByXPath("//div[starts-with(@class,'desktop-view')]"); var sizeDropdown = view.FindElements(By.XPath(".//select")); if (sizeDropdown.Count > 0) { var sizeElement = new SelectElement(sizeDropdown[0]); Thread.Sleep(1000); sizeElement.SelectByIndex(1); sizeDropdown[0].Click(); Thread.Sleep(5000); } var color = view.FindElements(By.XPath(".//div[@class='product__container__details__color__items']/div/input")); if (color.Count > 0) { color[0].Click(); Thread.Sleep(5000); } var size = view.FindElements(By.XPath(".//div[@class='product-form active']//input[@value != 'None']")); if (size.Count > 0) { size[0].Click(); Thread.Sleep(5000); } var addToCart = view.FindElements(By.XPath(".//div[@class='product__container__details__buynow active']//input")); if (addToCart.Count > 0) { try { addToCart[0].Click(); Thread.Sleep(5000); } catch { XtraMessageBox.Show("Product out of stock"); e.Result = true; return; } } var checkout = driver.FindElementByXPath("//a[starts-with(@class,'proceed')]"); checkout.Click(); Thread.Sleep(10000); js.ExecuteScript("window.scrollBy(0,500)"); var firstName = driver.FindElementById("firstNameShipping"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); firstName.SendKeys("Mark"); Thread.Sleep(2000); var lastName = driver.FindElementById("lastNameShipping"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); lastName.SendKeys("William"); Thread.Sleep(2000); var address = driver.FindElementById("addressShipping"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); address.SendKeys("Street #7, Parkinson Town"); Thread.Sleep(2000); var line2 = driver.FindElementById("line2Shipping"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); line2.SendKeys("Street #45, Bridge Town"); Thread.Sleep(2000); var city = driver.FindElementById("cityShipping"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); city.SendKeys("New York"); Thread.Sleep(2000); var state = driver.FindElementByXPath("//select[@id='stateShipping']"); var stateElement = new SelectElement(state); Thread.Sleep(1000); stateElement.SelectByIndex(5); state.Click(); Thread.Sleep(5000); var zipCode = driver.FindElementById("zipCodeShipping"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); zipCode.SendKeys("65000"); Thread.Sleep(2000); var phoneNo = driver.FindElementById("phoneNumber"); js.ExecuteScript("window.scrollBy(0,100)"); Thread.Sleep(5000); phoneNo.SendKeys("7478887753"); Thread.Sleep(2000); //var sameAddress = driver.FindElementByXPath("//label[@for='sameAddress']"); //js.ExecuteScript("window.scrollBy(0,100)"); //Thread.Sleep(5000); //sameAddress.Click(); e.Result = true; }
internal void InputUserName(string userName) { userNameLocator = driver.FindElementById("formField_username"); userNameLocator.SendKeys(userName); }
public void FindElementIfExists_ShouldReturnElement_WhenElementExists() { _Driver.FindElementById("root").FindElementIfExists(By.Id("testElementFindElementIfExists")).Should().NotBeNull(); }
public void ExractCouncil(string url, ref List <Documents> docs, ref List <QueryResult> queries) { WebClient c = new WebClient(); ChromeDriver cd = new ChromeDriver(); cd.Navigate().GoToUrl(url); System.Threading.Thread.Sleep(3000); IWebElement rangeEle = cd.FindElementByXPath("//select[@class='agendasearch-input']"); SelectElement rangeSelectEle = new SelectElement(rangeEle); rangeSelectEle.SelectByValue("cus"); System.Threading.Thread.Sleep(3000); IWebElement dateStartEle = cd.FindElementById("ctl00_ContentPlaceHolder1_SearchAgendasMeetings_radCalendarFrom_dateInput"); IWebElement dateEndEle = cd.FindElementById("ctl00_ContentPlaceHolder1_SearchAgendasMeetings_radCalendarTo_dateInput"); dateStartEle.Clear(); dateStartEle.SendKeys(this.dtStartFrom.ToString("M/d/yyyy")); dateEndEle.Clear(); dateEndEle.SendKeys(DateTime.Now.ToString("M/d/yyyy")); System.Threading.Thread.Sleep(2000); IWebElement searchBtnEle = cd.FindElementById("ctl00_ContentPlaceHolder1_SearchAgendasMeetings_imageButtonSearch"); searchBtnEle.Click(); System.Threading.Thread.Sleep(2000); while (true) { try { HtmlDocument doc = new HtmlDocument(); doc.LoadHtml(cd.PageSource); HtmlNodeCollection rowList = doc.DocumentNode.SelectNodes("//table[@id='ctl00_ContentPlaceHolder1_SearchAgendasMeetings_radGridMeetings_ctl00']/tbody/tr[contains(@class,'Row')]"); if (rowList != null) { foreach (HtmlNode rowNode in rowList) { HtmlNode meetingDateNode = rowNode.SelectSingleNode("./td"); string meetingText = meetingDateNode.InnerText; DateTime meetingDate = DateTime.ParseExact(meetingText, "MM/dd/yy", null); if (meetingDate < this.dtStartFrom) { Console.WriteLine("Too early, skip..."); continue; } HtmlNodeCollection docNodeList = rowNode.SelectNodes(".//a[contains(@href,'ashx')]"); if (docNodeList != null) { foreach (HtmlNode docNode in docNodeList) { string docUrl = docNode.Attributes["href"].Value; docUrl = docUrl.StartsWith("http") ? docUrl : url.Trim('#') + docUrl; Documents localdoc = docs.FirstOrDefault(t => t.DocSource == docUrl); if (localdoc == null) { string tag = docUrl.Contains("Minute") ? "Minute" : "Agenda"; localdoc = new Documents(); localdoc.DocId = Guid.NewGuid().ToString(); localdoc.CityId = this.cityEntity.CityId; localdoc.Checked = false; localdoc.Important = false; localdoc.DocType = "City Council"; localdoc.DocSource = docUrl; string localFile = string.Format("{0}\\Council_{1}_{2}.pdf", this.localDirectory, tag, meetingDate.ToString("yyyy-MM-dd")); localdoc.DocLocalPath = localFile; try { c.DownloadFile(docUrl, localFile); } catch { } docs.Add(localdoc); } else { Console.WriteLine("This file already downloaded..."); } this.ReadText(false, localdoc.DocLocalPath, ref localdoc); QueryResult qr = queries.FirstOrDefault(t => t.DocId == localdoc.DocId); if (qr == null) { qr = new QueryResult(); qr.CityId = localdoc.CityId; qr.DocId = localdoc.DocId; qr.MeetingDate = meetingDate; qr.SearchTime = DateTime.Now; queries.Add(qr); } this.ExtractQueriesFromDoc(localdoc, ref qr); Console.WriteLine("{0} docs added, {1} queries added...", docs.Count, queries.Count); this.SaveMeetingResultsToSQL(docs, queries); } } } } IWebElement nextPageBtnEle = cd.FindElementByXPath("//a[@title='Next Page']"); nextPageBtnEle.Click(); System.Threading.Thread.Sleep(3000); } catch (Exception ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Reach last page..."); Console.ResetColor(); break; } } cd.Quit(); cd = null; }
public static PortfolioInfo Capture() { var capture = new PortfolioInfo(); // // var options = new ChromeOptions(); // options.AddArgument("--disable-gpu"); // creates new chromeDriver and goes to webpage var chromeDriver = new ChromeDriver(@"./"); chromeDriver.Navigate().GoToUrl("https://login.yahoo.com/"); // waits for page to load // chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(14); // login sequence // chromeDriver.FindElementById("uh-signedin").Click(); chromeDriver.FindElementById("login-username").Click(); // chromeDriver.Keyboard.SendKeys(username); chromeDriver.Keyboard.SendKeys(usernamePassword.YahooUsername()); chromeDriver.Keyboard.SendKeys(Keys.Enter); chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); chromeDriver.FindElementById("login-passwd").Click(); // chromeDriver.Keyboard.SendKeys(password1); chromeDriver.Keyboard.SendKeys(usernamePassword.YahooPassword()); chromeDriver.Keyboard.SendKeys(Keys.Enter); //navigate to portfolio with stocks // chromeDriver.Navigate().GoToUrl("https://finance.yahoo.com/portfolios?bypass=true"); // chromeDriver.FindElementById("__dialog").Click(); // chromeDriver.Keyboard.SendKeys(Keys.Escape); //navigate to Jbristol Portfolio chromeDriver.Navigate().GoToUrl("https://finance.yahoo.com/portfolio/p_1/view/v2"); chromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); chromeDriver.FindElement(By.Id("__dialog")).Click(); chromeDriver.Keyboard.SendKeys(Keys.Escape); // get currentValue dayGains and totalGain var currentValue = chromeDriver .FindElementByXPath("//*[@id=\"main\"]/section/header/div/div[1]/div/div[2]/p[1]").Text; var dayGain = chromeDriver .FindElementByXPath("//*[@id=\"main\"]/section/header/div/div[1]/div/div[2]/p[2]/span").Text.Split(' '); var totalGain = chromeDriver .FindElementByXPath("//*[@id=\"main\"]/section/header/div/div[1]/div/div[2]/p[3]/span").Text.Split(' '); var dayGainPercent = dayGain[1]; var totalGainPercent = totalGain[1]; capture.CaptureDate = DateTime.Now; capture.PortfolioValue = double.Parse(currentValue, NumberStyles.Currency); capture.DayGain = double.Parse(dayGain[0]); // capture.PercentDayGain = double.Parse(dayGainPercent.Remove(0, 1).Remove(dayGainPercent.Length - 2, dayGainPercent.Length - 1)); capture.PercentDayGain = (double.Parse(dayGainPercent.Trim(new char[] { ' ', '(', '%', ')' })) / 100); capture.TotalGain = double.Parse(totalGain[0]); // capture.PercentTotalGain = double.Parse(totalGainPercent.Remove(0, 1).Remove(dayGainPercent.Length - 2, dayGainPercent.Length - 1)); capture.PercentTotalGain = (double.Parse(totalGainPercent.Trim(new char[] { ' ', '(', '%', ')' })) / 100); // Console.WriteLine( // "currentValue: {0}, dayGain: {1}, totalGain: {2}, dayGainPercent: {3}, totalGainPercent: {4}", // PortfolioValue, DayGain, TotalGain, PercentDayGain, PercentTotalGain); // // scrape symbols var portfolioStockInfo = new List <StockInfo>(); // var table = chromeDriver.FindElement(By.TagName("table")); var table = chromeDriver.FindElement(By.ClassName("tJDbU")); // Console.WriteLine("Table" + table); // var tableRows = table.FindElements(By.TagName("tr")); var tableRows = table.FindElements(By.ClassName("_14MJo")); Console.WriteLine("tablerows" + tableRows.Count); var listRowData = new List <string>(); // each row in the table foreach (var row in tableRows) { var tableColumn = row.FindElements(By.TagName("td")); if (tableColumn.Count > 0) { foreach (var col in tableColumn) { listRowData.Add(col.Text); } var symbolPrice = listRowData[0].Split("\n"); var changePercentDollar = listRowData[1].Split("\n"); var dayGainPercentDollar = listRowData[5].Split("\n"); var totalGainPercentDollar = listRowData[6].Split("\n"); var numLots = listRowData[7].Split(' '); portfolioStockInfo.Add(new StockInfo() { StockSymbol = symbolPrice[0], StockCurrentPrice = symbolPrice[1], StockPriceChange = changePercentDollar[1], StockPriceChangePercent = changePercentDollar[0].Trim(new char[] { ' ', '+', '%' }), StockShares = listRowData[2], StockCostBasis = listRowData[3], StockMarketValue = listRowData[4], StockDayGain = dayGainPercentDollar[1], StockDayGainPercent = dayGainPercentDollar[0].Trim(new char[] { ' ', '+', '%' }), StockTotalGain = totalGainPercentDollar[1], StockTotalGainPercent = totalGainPercentDollar[0].Trim(new char[] { ' ', '+', '%' }), StockLots = numLots[0], StockNotes = listRowData[8] }); foreach (var info in portfolioStockInfo) { Console.WriteLine("Info: " + info); } } Console.WriteLine("going to clear"); listRowData.Clear(); } chromeDriver.Quit(); // Console.WriteLine("portfolioStockInfo: " + portfolioStockInfo); capture.StockInfo = portfolioStockInfo; return(capture); }
/// <summary> /// Grab Dribble data /// </summary> /// <param name="chromeOptions"></param> private static void GrabDribbleData(ChromeOptions chromeOptions) { try { // Initialize the Chrome Driver using (var driver = new ChromeDriver(chromeOptions)) { // Go to the home page driver.Navigate().GoToUrl("https://dribbble.com/"); Thread.Sleep(5000); var linkLogin = driver.FindElementById("t-signin"); linkLogin.Click(); Thread.Sleep(5000); // Get the page elements var txtUserName = driver.FindElementById("login"); var txtPassword = driver.FindElementById("password"); var btnLogin = driver.FindElementByClassName("button"); // get user name and password from App Setting string strUserName = ConfigurationManager.AppSettings["username"]; txtUserName.SendKeys(strUserName); //website has two password text boxes. So I have to click in first then put password in second to make it working. string strPassword = ConfigurationManager.AppSettings["password"]; txtPassword.SendKeys(strPassword); Thread.Sleep(5000); // and click the login button btnLogin.Click(); Thread.Sleep(5000); var browser = new ScrapingBrowser(); string baseLink = "https://dribbble.com/designers"; WebPage pageResp = browser.NavigateToPage(new Uri(baseLink)); var li = pageResp.Html.SelectNodes(".//div[@class='results-pane']/ol/li"); foreach (var item in li) { if (!string.IsNullOrEmpty(item.InnerText)) { Console.WriteLine("----------------------------------------------------------------------------------------------------------------------------------------"); //get all designers and terms step by step string pattern = "<a\\s+(?:[^>]+\\s+)?class\\s*=\\s*(?:jobs-mark(?=\\s|>)|(['\"])(?:(?:(?!\\1).)*?\\s+)*jobs-mark(?:\\s+(?:(?!\\1).)*?)*\\1)[^>]*>(.*?)</a>"; var inner = Regex.Match(item.InnerHtml, pattern, RegexOptions.Singleline); var getHrefValue = Regex.Match(inner.Value, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value; var finalValue = getHrefValue.Split('/')[1]; string baseURL = "https://dribbble.com/"; string designerUrl = baseURL + finalValue; //get all profile details WebPage getInformation = browser.NavigateToPage(new Uri(designerUrl)); string getNameInfo = string.Empty; var nameDetails = getInformation.Html.SelectNodes(".//div[@class='profile-info-mod profile-essentials']/h1/a"); if (nameDetails != null) { getNameInfo = Regex.Replace(nameDetails[0].InnerText, @"\t|\n|\r", "").Trim(); } string getAddressInfo = string.Empty; var addressDetails = getInformation.Html.SelectNodes(".//div[@class='profile-info-mod profile-essentials']/h1/span[@class='location']/span"); if (addressDetails != null) { getAddressInfo = Regex.Replace(addressDetails[0].InnerText, @"\t|\n|\r", "").Trim(); } string getPersonalInfo = string.Empty; var personnelInformation = getInformation.Html.SelectNodes(".//div[@class='bio']"); if (personnelInformation != null) { getPersonalInfo = Regex.Replace(personnelInformation[0].InnerText, @"\t|\n|\r", "").Trim(); } Console.WriteLine("******* *Main Information* **************"); Console.WriteLine("Name: " + getNameInfo + "\n" + "Location: " + getAddressInfo + "\n" + "Bio: " + getPersonalInfo); var skillList = getInformation.Html.SelectNodes(".//div[@class='floating-sidebar-float']/div/ul/li"); if (skillList != null) { Console.WriteLine("************** *Skills* **************"); foreach (var skill in skillList) { string data = Regex.Replace(skill.InnerText, @"\t|\n|\r", ""); string URL = Regex.Match(skill.InnerHtml, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value; Console.WriteLine(data.Trim() + " " + baseURL + URL); } } var onTeams = getInformation.Html.SelectNodes(".//div[@class='floating-sidebar-extra']/div[@class='profile-info-mod']/ul[@class='profile-details on-teams']/li"); if (onTeams != null) { Console.WriteLine("************** *ON TEAMS* **************"); foreach (var team in onTeams) { string data = Regex.Replace(team.InnerText, @"\t|\n|\r", ""); string URL = Regex.Match(team.InnerHtml, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value; Console.WriteLine(data.Trim() + " " + baseURL + URL); } } var otherDetails = getInformation.Html.SelectNodes(".//div[@class='floating-sidebar-extra']/div[@class='profile-info-mod']/ul[@class='profile-details']/li"); if (otherDetails != null) { Console.WriteLine("************** *ELSEWHERE* **************"); foreach (var elseWhere in otherDetails) { string data = Regex.Replace(elseWhere.InnerText, @"\t|\n|\r", ""); string URL = Regex.Match(elseWhere.InnerHtml, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value; Console.WriteLine(data.Trim() + " " + baseURL + URL); } } var projectList = getInformation.Html.SelectNodes(".//div[@class='floating-sidebar-extra']/div[@class='profile-info-mod']/ul[@class='profile-projects']/li"); if (projectList != null) { Console.WriteLine("************** *PROJECTS* **************"); foreach (var project in projectList) { string data = Regex.Replace(project.InnerText, @"\t|\n|\r", "").Trim(); string URL = Regex.Match(project.InnerHtml, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value; Console.WriteLine(data.Replace(" ", String.Empty) + " " + baseURL + URL); } } var featuredList = getInformation.Html.SelectNodes(".//div[@class='floating-sidebar-extra']/div[@class='profile-info-mod']/ul[@class='profile-details profile-featured']/li"); if (featuredList != null) { Console.WriteLine("************** *FEATURED* **************"); foreach (var feature in featuredList) { string data = Regex.Replace(feature.InnerText, @"\t|\n|\r", ""); string URL = Regex.Match(feature.InnerHtml, "href\\s*=\\s*\"(?<url>.*?)\"").Groups["url"].Value; Console.WriteLine(data.Trim() + " " + baseURL + URL); } } } } Console.ReadLine(); } } catch (Exception ex) { Console.WriteLine(ex.InnerException); Console.ReadLine(); } }
public void CliquearCategoriaIsOk() { Optica.Url = Global.URL; Optica.FindElementById("UsernameLogin").SendKeys("Anderson"); Optica.FindElementById("passwordLogin").SendKeys("12345678"); Optica.FindElementById("Login").Click(); Optica.FindElementById("CategoriasLink").Click(); Assert.AreEqual("http://localhost:51542/Category/List", Optica.Url);//Para ver si la url es la misma que abre chrome Optica.Close(); }
static void FillPassengerDetails(ChromeDriver driver) { // //*[@id="addPassengerForm:psdetail:0"]/td[2]/input IWebElement PassengerNameCell = driver.FindElementByXPath("//*[@id=\"addPassengerForm:psdetail:0\"]/td[2]/input"); PassengerNameCell.SendKeys(PassengerName); IWebElement boardingStation = driver.FindElementById("addPassengerForm:boardingStation"); boardingStation.SendKeys(BoardingStation); IWebElement PassengerAgeCell = driver.FindElementById("addPassengerForm:psdetail:0:psgnAge"); PassengerAgeCell.SendKeys(PassengerAge); IWebElement PassengerGenderCell = driver.FindElementById("addPassengerForm:psdetail:0:psgnGender"); PassengerGenderCell.SendKeys(PassengerGender); IWebElement PassengerBerthCell = driver.FindElementById("addPassengerForm:psdetail:0:berthChoice"); PassengerBerthCell.SendKeys(PassengerBerthPreference); IWebElement PassengerMobileNumberInputTextbox = driver.FindElementById("addPassengerForm:mobileNo"); PassengerMobileNumberInputTextbox.Clear(); PassengerMobileNumberInputTextbox.SendKeys(PassengerMobileNumber); try { IWebElement PassengerFoodChoice = driver.FindElementById("addPassengerForm:psdetail:0:foodChoice"); PassengerFoodChoice.SendKeys(FoodChoice); } catch (NoSuchElementException e) { } IWebElement autoUpgrade = driver.FindElementById("addPassengerForm:autoUpgrade"); autoUpgrade.Click(); try { IWebElement confirmBerths = driver.FindElementById("addPassengerForm:onlyConfirmBerths"); confirmBerths.Click(); } catch (Exception e) { Console.WriteLine("Confirm berths are not alloted !!! \n PRESS ANY KEY TO CONTINUE BOOKING OR CLOSE THE CONSOLE WINDOW TO STOP"); Console.ReadKey(); } while (true) { Console.WriteLine("Enter Captcha"); string captcha = Console.ReadLine(); IWebElement Captcha = driver.FindElementById("nlpAnswer"); Captcha.SendKeys(captcha); IWebElement next = driver.FindElementById("validate"); next.Click(); try { IWebElement popUp = driver.FindElementById("addPassengerForm:waitOnPPPopup"); while (!popUp.GetAttribute("style").Contains("hidden")) { Thread.Sleep(250); } } catch (Exception e) { } try { Captcha = driver.FindElementById("nlpAnswer"); continue; } catch (Exception e) { break; } } }
public void CheckPage() { // if (!welcome && driver.FindElementsByCssSelector("div[data-test-id='nux_name_done_btn']").Count != 0) { try { driver.FindElementByCssSelector("div[data-test-id='nux_name_done_btn']").Click(); Console.WriteLine("press next"); welcome = true; return; } catch { return; } } if (!skip && driver.FindElementsByCssSelector("button[data-test-id='nux-ext-skip-btn']").Count != 0) { try { driver.FindElementByCssSelector("button[data-test-id='nux-ext-skip-btn']").Click(); Console.WriteLine("press skip"); skip = true; return; } catch { return; } } //if (welcome && !gender && driver.FindElementsByCssSelector(".NuxGenderStep__headerContent").Count == 1) //{ // var buttons = driver.FindElementsByTagName("button"); // foreach (var item in buttons) // { // if (item.Text.ToLower().Contains("female")) // { // item.Click(); // } // } // //Female //} if (!gender && driver.FindElementsByCssSelector("label[for='female']").Count > 0) { try { var x = driver.FindElementsByCssSelector("label[for='female']"); x[0].Click(); gender = true; return; } catch { return; } } if (!country && driver.FindElementById("newUserCountry") != null) { try { driver.FindElementByCssSelector(".NuxContainer__NuxStepContainer button").Click(); country = true; return; } catch { } try { driver.FindElementByCssSelector("div[data-test-id=nux-locale-country-next-btn]").Click(); country = true; return; } catch { } } if (!country && driver.FindElementByCssSelector(".NuxContainer__NuxStepContainer button") != null) { try { driver.FindElementByCssSelector(".NuxContainer__NuxStepContainer button").Click(); country = true; return; } catch { return; } } if (!card && driver.FindElementsByCssSelector("[aria-label='Interest card']").Count > 1) { int result = 0; Save(); var cards = driver.FindElementsByCssSelector("[aria-label='Interest card']"); for (int i = 0; i < 100; i++) { if (result > 5) { var button = driver.FindElementsByCssSelector("[data-test-id='nux-picker-done-btn'] button"); if (button.Count > 0) { button[0].Click(); card = true; break; } button = driver.FindElementsByCssSelector("button[type='submit']"); if (button.Count > 0) { button[0].Click(); card = true; break; } } try { OpenQA.Selenium.Interactions.Actions action = new OpenQA.Selenium.Interactions.Actions(driver); // action.MoveToElement(cards[i]).DoubleClick().Build().Perform(); action.MoveToElement(cards[i]).DoubleClick().Build().Perform(); // WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a")); // action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform(); //} //cards[i].Click(); result++; } catch (Exception ex) { Console.WriteLine(ex.Message); cards = driver.FindElementsByCssSelector(".NuxInterest"); //return; } // return; } } if (!scip && card && driver.FindElementsByCssSelector(".NuxExtensionUpsell__optionalSkip").Count != 0) { try { var scripButton = driver.FindElementsByCssSelector(".NuxExtensionUpsell__optionalSkip"); scripButton[0].Click(); scip = true; return; } catch { return; } } if (card && !main) { try { var body = driver.FindElementsByCssSelector(".mainContainer"); //if(body.Count > 0) body[0].Click(); Thread.Sleep(TimeSpan.FromSeconds(15)); var buttons = driver.FindElementsByTagName("button"); foreach (IWebElement button in buttons) { Console.WriteLine(button.Text); if (button.Text.Contains("Got")) { OpenQA.Selenium.Interactions.Actions action = new OpenQA.Selenium.Interactions.Actions(driver); action.MoveToElement(button).DoubleClick().Build().Perform(); } } Thread.Sleep(TimeSpan.FromSeconds(5)); driver.FindElementByTagName("body").Click(); driver.Url = "https://www.pinterest.com/"; Thread.Sleep(TimeSpan.FromSeconds(15)); main = true; return; } catch { return; } } if (main && !url) { try { Thread.Sleep(TimeSpan.FromSeconds(5)); if (driver.Url.EndsWith("/settings/")) { url = true; } driver.Url = "https://pinterest.com/settings"; } catch { } } if (url && !settings) { try { for (int i = 0; i < 50; i++) { driver.FindElementById("first_name").SendKeys(Keys.Backspace); driver.FindElementById("last_name").SendKeys(Keys.Backspace); driver.FindElementById("username").SendKeys(Keys.Backspace); } //var selectElement = new SelectElement(driver.FindElementById("accountBasicsCountry")); //selectElement.SelectByValue("US"); driver.FindElementById("first_name").SendKeys(PrettyName()); driver.FindElementById("last_name").SendKeys(PrettyName()); string[] cities = File.ReadAllLines("city_names.txt"); driver.FindElementById("location").SendKeys(cities[new Random().Next(0, cities.Count())]); string userName = prettyName + new Random().Next(); driver.FindElementById("username").SendKeys(userName); // string userName = driver.FindElementById("userUserName").GetAttribute("value"); //malmopianoilianaruby SaveSettings(); settings = true; //$$("input[type=file]") Thread.Sleep(new TimeSpan(0, 0, 5)); driver.Quit(); //data-test-id="createBoardCard" // tut driver.Url = "https://pinterest.com/" + userName + "/boards"; Thread.Sleep(new TimeSpan(0, 0, 5)); var createBoards = driver.FindElementsByCssSelector("[data-test-id=createBoardCard]"); Thread.Sleep(new TimeSpan(0, 0, 5)); foreach (var item in createBoards) { if (item.Enabled && item.Displayed) { item.Click(); } } var input = driver.FindElementById("boardEditName"); input.SendKeys(prettyName); var buttonsCreate = driver.FindElementsByTagName("button"); foreach (var item in buttonsCreate) { if (item.Text.Contains("Create") && item.Enabled && item.Displayed) { item.Click(); Thread.Sleep(new TimeSpan(0, 0, 15)); AddImage(); } } } catch { } } }
///<summary> ///Navigates browser to specified url. Grabs Price and Name of Product by either their HTML ID or CSS Class. ///</summary> public void getPrice(string url, string titleId, string priceId, ChromeDriver browser, int productId) { string Price; string title; //the web can be a tricky, unreliable place, best to wrap this in a try/catch block: try { browser.Navigate().GoToUrl(url); var timeStamp = DateTime.Now; try { Price = browser.FindElementById(priceId).Text; } catch (Exception e1) { try { Console.WriteLine("No element by id, trying css class: \n" + e1.ToString()); Price = browser.FindElementByClassName(priceId).Text; } catch (Exception e2) { Console.WriteLine("Unable to retreive price by id or css: " + priceId + "\n" + e2.ToString()); Price = "Error"; } } try { title = browser.FindElementById(titleId).Text; } catch (Exception e1) { try { Console.WriteLine("No element by id, trying css class: \n" + e1.ToString()); title = browser.FindElementByClassName(titleId).Text; } catch (Exception e2) { Console.WriteLine("Unable to retreive title by id or css: " + titleId + "\n" + e2.ToString()); title = "Error"; } } Console.WriteLine($"Object Found:\nName:{title}\nPrice:{Price}\nURL:{url}\nTime:{timeStamp.ToString()}"); var test = _dbContext.ProductMeta.Find(productId); var newProduct = new Product { timeRetreived = timeStamp, price = Price, name = title, }; _dbContext.SaveChanges(); // var ParentProduct = Program.globalContext.ProductMeta.Find(productId); // var foundProduct = new Product // { // timeRetreived = timeStamp, // price = Price, // name = title, // }; // ParentProduct.products.Add(foundProduct); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public void DebeIngresarYMostrarRegistroDeGasto() { Banco.Url = Global.URL; Banco.FindElementById("Crear").Click(); Assert.IsTrue(Banco.Url.EndsWith("GastoTarj/Crear?IdCuenta=1")); Banco.Close(); }
public string Spa122(ChromeDriver browser) { string ATAInfo = ""; try { browser.FindElementByName("user").SendKeys(userName); browser.FindElementByName("pwd").SendKeys(passWord); //login button? no unique ID for it so trying this way, hopefully I can count browser.FindElements(By.TagName("input"))[5].Click(); } catch (ElementNotVisibleException e) { Console.WriteLine($"Ran into error: {e.ToString()} \nAttempting refresh of page."); //sometimes page wouldn't load for spa122, will attempt a refresh, but this could go on endlessly soooo //nvm just re run old code vs callin whole method. browser.Navigate().Refresh(); browser.FindElementByName("user").SendKeys(userName); browser.FindElementByName("pwd").SendKeys(passWord); //login button? no unique ID for it so trying this way, hopefully I can count browser.FindElements(By.TagName("input"))[5].Click(); // throw; } catch (Exception e) { return(ATAInfo = $"Some error occured logging into ATA, ref: {e.ToString()}"); } try { //Go to network setup page. browser.FindElementById("trt_Network_Service.asp").Click(); var networkSettings = browser.FindElementById("d_4"); networkSettings.FindElement(By.TagName("a")).Click(); //Show DHCP reservations. browser.FindElementById("t3").Click(); //id's could be numbered like an array? need to find an spa122 with mulitples to test that, too bad they're becoming rare...or is it that bad? lolol var DHCP_Name = browser.FindElementByName("dhcp_select_name_0"); var DHCP_IP = browser.FindElementByName("dhcp_select_ip_0"); var DHCP_MAC = browser.FindElementByName("dhcp_select_mac_0"); ATAInfo += $"DCHP item: \nName:{DHCP_Name.Text}\nLAN IP: {DHCP_IP.Text}\nMAC: {DHCP_MAC.Text}"; } catch (NotFoundException NotHere) { Console.WriteLine($"Nothing found in DHCP Table {NotHere.ToString()}"); ATAInfo += "Nothing found in DCHP table\n"; //throw; } catch (Exception e) { return(ATAInfo = $"Couldn't get into ATA {e.ToString()}"); } //Considering there's only one ethernet port on the SPA122, will assume there's one item in DHCP, not always 100% //accurate as not every customer lets SPA122 run DHCP, but should be enough to go off of as far as equipment functionality //ATAInfo += $"Number of items found in DHCP: {DHCP_IP.Count.ToString()}"; //Console.WriteLine($"Number of items found in DHCP: {DHCP_IP.Count.ToString()}"); //for (int dhcp_list = 0; dhcp_list >= DHCP_IP.Count; dhcp_list++) //{ // ATAInfo += $"DHCP client name: {DHCP_Name[dhcp_list].Text} IP: {DHCP_IP[dhcp_list].Text} MAC: {DHCP_MAC[dhcp_list].Text}"; // Console.WriteLine($"DHCP client name: {DHCP_Name[dhcp_list].Text} IP: {DHCP_IP[dhcp_list].Text} MAC: {DHCP_MAC[dhcp_list].Text}"); //} try { //Check phones browser.FindElementById("trt_voice.asp").Click(); //this page is a mess, hope we really REALLY can count...you really don't wanna see this DOM man. but if you do uncomment this next line, ye be warned //Console.WriteLine(browser.PageSource.ToString()); //Data I want is stored in iframe will have to switch in and out of it. browser.SwitchTo().Frame(browser.FindElementById("iframe")); //Should be leading DIV containing ALL the info related to voice/uptime. var infoDiv = browser.FindElementById("Information"); var infoTable = infoDiv.FindElements(By.TagName("tr"))[8]; infoTable = infoTable.FindElements(By.TagName("td"))[3]; ATAInfo += $"ATA up time: {infoTable.FindElement(By.TagName("font")).Text}"; //Line 1: infoTable = infoDiv.FindElements(By.TagName("tr"))[16]; ATAInfo += $"Line 1 is {infoTable.FindElements(By.TagName("font"))[0].Text} hook and {infoTable.FindElements(By.TagName("font"))[1].Text} to SIP Server"; //line 2 infoTable = infoDiv.FindElements(By.TagName("tr"))[43]; //yeah that many rows in this table ATAInfo += $"Line 2 is {infoTable.FindElements(By.TagName("font"))[0].Text} hook and {infoTable.FindElements(By.TagName("font"))[1].Text} to SIP Server"; } catch (Exception NoIframe) { ATAInfo += $"Couldn't get voice info, no Iframe found or trouble switching to Iframe, ref: {NoIframe.ToString()}"; Console.WriteLine($"Couldn't get voice info, no Iframe found or trouble switching to Iframe, ref: {NoIframe.ToString()}"); throw; } Console.WriteLine("Going to reboot ATA..."); //Getting out of iframe, back into orginal DOM browser.SwitchTo().DefaultContent(); //move to reboot ATA browser.FindElementById("trt_Management.asp").Click(); var adminPage = browser.FindElementById("d_20"); //should be reboot button. adminPage.FindElement(By.TagName("a")).Click(); browser.FindElementById("t4").Click(); //handle JS alert try { BrowserHelper.HandleAlerts(browser); } catch (NoAlertPresentException BadAlert) { Console.WriteLine($"No alert found when attempting reboot, are lines in use? ref: {BadAlert.ToString()}"); ATAInfo += "No alert found when attempting reboot, are lines in use?"; // throw; } return(ATAInfo); }
public void WhenISearchForMuppets() { _driver.FindElementById("lst-ib").SendKeys("muppets"); _driver.FindElementByClassName("lsb").Click(); }
public void NavigateToPage() { var username = user; var password = pass; _chrome.Navigate().GoToUrl("http://localhost:5000/Authentication/Login"); _chrome.FindElementById("Username").SendKeys(username); _chrome.FindElementById("Password").SendKeys(password); _chrome.FindElementById("Login").Click(); Assert.Contains(username.ToLower(), _chrome.FindElementById("DashboardMsg").Text.ToLower()); _chrome.FindElementByLinkText("Profile").Click(); Assert.Contains("User Profile", _chrome.FindElementById("Profile").Text); _chrome.FindElementByLinkText("Change Password").Click(); Assert.Contains("Change Password", _chrome.FindElementByClassName("form-signin-heading").Text); _chrome.Close(); }
public static IWebElement FindLabelTarget(this ChromeDriver driver, IWebElement label) { return(driver.FindElementById(label.GetAttribute("for"))); }
public void ClickTheNotifySufficientCapacityNode() { Driver.FindElementById("ctl00_ctl03_wftt15").Click(); }
public void QuandoPreencherONomeDoProduto() { _browser.FindElementById("Nome").SendKeys("mouse3"); }