/// <summary> /// Finds the elements with timeout wait. /// </summary> /// <param name="driver">The driver.</param> /// <param name="by">The by.</param> /// <returns></returns> public static ReadOnlyCollection<IWebElement> FindElementsWithTimeoutWait(IWebDriver driver, By by) { Exception ex = null; ReadOnlyCollection<IWebElement> e = null; long elapsedTime = 0; while (elapsedTime < TimeOut) { try { elapsedTime++; StandardSleep(1); e = driver.FindElements(by); break; } catch (NoSuchElementException nse) { if (e == null) throw ex; } } if (e == null) throw ex; return e; }
public static bool FillOutLoginForm(IWebDriver driver, string username, string password, IWebElement submitButton = null, IWebElement usernameField = null, IWebElement passwordField = null) { try { if (usernameField == null && driver.FindElements(By.XPath(txtUsernameXPath)).Count > 0) usernameField = driver.FindElement(By.XPath(txtUsernameXPath)); if (passwordField == null && driver.FindElements(By.XPath(txtPasswordXPath)).Count > 0) passwordField = driver.FindElement(By.XPath(txtPasswordXPath)); if (submitButton == null && driver.FindElements(By.XPath(btnSubmitXPath)).Count > 0) submitButton = driver.FindElement(By.XPath(btnSubmitXPath)); if (usernameField != null && passwordField != null && submitButton != null) { usernameField.SendKeys(username); passwordField.SendKeys(password); submitButton.SendKeys(Keys.Enter); return true; } return false; } catch (IllegalLocatorException e) { return false; } }
public CommandResult Execute(IWebDriver driver, CommandDesc command) { try { var result = new CommandResult { Command = command }; var timeout = GetTimeout(command); var complexSelector = WebDriverExtensions.GetContainsSelector(command.Selector); var by = WebDriverExtensions.GetBy(complexSelector.SimpleSelector); var elements = driver.FindElements(by); if (elements.Any()) driver.WaitForNotElement(by, timeout.GetValueOrDefault(WebDriverExtensions.DEFAULT_TIMEOUT)); elements = driver.FindElements(by); var count = elements.Count(); if (count > 0) throw new Exception("Element was found."); return result; } catch (Exception ex) { return new CommandResult { Command = command, HasError = true, Comments = ex.Message }; } }
private static void AssetSelection(IWebDriver driver) { for (var n = 0; n <= 1; n++) { driver.FindElement(By.CssSelector("img.img-responsive.center-block")).Click(); driver.FindElement(By.Id("s2id_autogen1")).Click(); var groups = new SelectElement(driver.FindElement(By.Id("groups"))); groups.SelectByIndex(n); var assetType = groups.SelectedOption.Text; driver.FindElement(By.CssSelector("button.btn.gradient")).Click(); //click search //Groups dropdown IList<IWebElement> details = driver.FindElements(By.LinkText("Details")); Console.WriteLine("There are {0} {1} ", details.Count(), assetType); NavigateGroups(driver, details); // driver.FindElement(By.CssSelector("img.img-responsive.center-block")).Click(); // driver.FindElement(By.CssSelector("a.select2-search-choice-close")).Click(); //clear } //Console.ReadKey(); }
public void TheXTest() { driver = new FirefoxDriver(); IJavaScriptExecutor js = driver as IJavaScriptExecutor; Login u = new Login(driver); string login1 = "guest"; u.get().login(login1, login1).click();//вход на сайт driver.FindElement(By.Id("sovzond_widget_SimpleButton_104")).Click(); Thread.Sleep(5000); IWebElement element = driver.FindElement(By.Id("sovzond_widget_SimpleButton_0")); var builder = new Actions(driver); builder.Click(element).Perform(); IList<IWebElement> el = driver.FindElements(By.ClassName("svzLayerManagerItem")); for (int n = 0; n < el.Count; n++) { if (el[0].Text != "Google") Assert.Fail("не найден Google"); if (el[4].Text != "Росреестр") Assert.Fail("не найден Росреестр"); if (el[5].Text != "OpenStreetMap") Assert.Fail("не найден OpenStreetMap"); if (el[6].Text != "Топооснова") Assert.Fail("не найден Топооснова"); } IWebElement element1 = driver.FindElement(By.Id("dijit_form_RadioButton_3")); builder.Click(element1).Perform(); Thread.Sleep(5000); string h= (string)js.ExecuteScript("return window.portal.stdmap.map.baseLayer.div.id.toString()"); }
public static void logout(IWebDriver driver) { driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0)); System.Collections.ObjectModel.ReadOnlyCollection<IWebElement> e = driver.FindElements(By.LinkText("Logout")); if (e.Count > 0) e.First().Click(); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(Config.implicitTimeout)); }
/// <summary> /// forが含まれているタグを検索しクリックする /// </summary> /// <param name="webDriver">webDriver</param> /// <param name="name">name</param> public void ClickFor(IWebDriver webDriver, string contain) { try { IList<IWebElement> tag_input = webDriver.FindElements(By.XPath(string.Format("//*[contains(@for,'{0}')]", contain))); capche.SaveCapche(webDriver); foreach (IWebElement tag in tag_input) { if (tag.Displayed) { tag.Click(); return; } } throw new OriginalException(string.Format("contain:{0}, Not Found", contain)); } catch (Exception ex) { throw new OriginalException(string.Format("containUrl:{0}, ClickFor, ErrorMessage:{1}", contain, ex.Message)); } finally { capche.SaveCapche(webDriver); } }
public void HandleElement(IWebElement el, IWebDriver browser, string[] parameters) { var targetvalue = parameters[2]; el.Click(); IList<IWebElement> comboItems = browser.FindElements(By.CssSelector(".x-boundlist .x-boundlist-item")); comboItems.First(item => item.Text.Trim() == targetvalue).Click(); }
public List<IWebElement> GetLinks(IWebDriver driver) { if (_pageLinks == null) { _pageLinks = driver.FindElements(By.TagName("a")).ToList(); } return _pageLinks; }
public static bool CheckElementExists(string CssSelector, IWebDriver d) { IList<IWebElement> eleList = d.FindElements(By.CssSelector(CssSelector)); if (eleList.Count > 0) { return true; } return false; }
public void Culture(IWebDriver driver, Datarow datarow) { try { driver.FindElement(By.LinkText("MoShop")).Click(); driver.FindElement(By.CssSelector("#IndexMenuLeaf3 > a")).Click(); driver.FindElement(By.LinkText("testshop")).Click(); driver.FindElement(By.LinkText("Shop")).Click(); try { driver.FindElement(By.CssSelector("h3.collapsible.collapsed")).Click(); driver.FindElement(By.CssSelector("h3.collapsible.collapsed")).Click(); } catch (Exception ex) { ex.ToString(); } driver.FindElement(By.Id("CustomDomainName")).SendKeys("m.testshop.com"); driver.FindElement(By.CssSelector("input.button")).Click(); new SelectElement(driver.FindElement(By.Id("DefaultCultureSelected"))).SelectByText( "Telugu (India) - ₹ [te-IN]"); driver.FindElement(By.CssSelector("input.button")).Click(); decimal count = driver.FindElements(By.XPath("//div[@id='CataloguesControl']/div/table/tbody/tr")).Count; for (var i = 1; i <= count; i++) { var name = GetValue(driver, By.XPath("//div[@id='CataloguesControl']/div/table/tbody/tr[" + i + "]/td/input"), 30); if (name != "Default") continue; driver.FindElement(By.XPath("//*[@id='CataloguesControl']/div/table/tbody/tr[" + i + "]/th[2]/a")) .Click(); driver.FindElement(By.CssSelector("input.button")).Click(); new SelectElement(driver.FindElement(By.Id("Culture_Value"))).SelectByText( "Telugu (India) - ₹ [te-IN]"); driver.FindElement(By.CssSelector("input.button")).Click(); break; } //Inserting Category Images. new CategoryImages().Images(driver, datarow); driver.Navigate().GoToUrl("http://m.testshop.com"); var url = driver.Url; datarow.Newrow("Customa Domain Name", "http://m.testshop.com/", url, url == "http://m.testshop.com" ? "PASS" : "FAIL", driver); } catch (Exception ex) { var e = ex.ToString(); datarow.Newrow("Exception", "Exception Not Exopected", e, "PASS", driver); } }
public void Page_Chrome_ShouldContain_DisplayFor_FirstName() { //Arrange _webDriver = WebDriver.InitializeChrome(); _webDriver.Navigate().GoToUrl("http://localhost/TestDrivingMVC.Web/Customer/Index/1"); //Act IWebElement result = _webDriver.FindElements(By.TagName("label")).FirstOrDefault(x => x.Text == "First Name"); //Assert result.Should().NotBeNull(); }
private static IWebElement GetElements(IWebDriver driver, string query, int index) { var elements = driver.FindElements(By.XPath(query)); if (!elements.Any()) { throw new Exception(string.Format("No elements returned with query {0} looking for index {1}", query, index)); } return elements[index]; }
private static IEnumerable<IWebElement> FindElements(IWebDriver driver, By selector) { try { return driver.FindElements(selector); } catch (NoSuchElementException) { return null; } }
public static ReadOnlyCollection<IWebElement> WaitingFor_GetElementsWhenExists(IWebDriver driver, By by, TimeSpan timeOut) { ReadOnlyCollection<IWebElement> elements; var wait = new WebDriverWait(driver, timeOut); try { wait.Until(ExpectedConditions.ElementExists(by)); elements = driver.FindElements(by); } catch { elements = null; } return elements; }
public void FirstNameIsRequired_ValidationMessage_ShouldNotBeDisplayed_WhenClickingCreate_With_FirstName_Field_FilledIn_Chrome() { //Arrange _webDriver = WebDriver.InitializeChrome(); _webDriver.Navigate().GoToUrl(url); _webDriver.FindElement(By.Id("FirstName")).SendKeys("Hodor! Hodor!"); _webDriver.FindElement(By.Id("create")).Click(); //Act var result = _webDriver.FindElements(By.TagName("span")).FirstOrDefault(x => x.Text == "First Name is required"); //Assert result.Should().BeNull(); }
public static ReadOnlyCollection<IWebElement> FindElements(IWebDriver driver, By by, int timeoutInSeconds) { if (timeoutInSeconds > 0) { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); return wait.Until(currentDriver => (currentDriver.FindElements(by).Count > 0) ? currentDriver.FindElements(by) : null); } else { return driver.FindElements(by); } }
private void GoToCoordWnd(IWebDriver driver) { driver.FindElement(By.ClassName("gotoCoordsButton")).Click(); //делаем клик по иконке XY IList<IWebElement> elsTitle = driver.FindElements(By.ClassName("containerTitle")); //ищем текст "ПЕРЕХОД ПО КООРДИНАТАМ", при не нахождении возникает ошибка if (getElementByText(elsTitle, "ПЕРЕХОД ПО КООРДИНАТАМ") == null) { Assert.Fail("ПЕРЕХОД ПО КООРДИНАТАМ не найден"); } InputCoordWnd.get(driver).setLon(60, 50, 50).setLat(69, 59, 0).click();//нажимаем клавишу найти }
public IList<ITestResult> GetResults(IWebDriver webDriver) { var testResults = new List<ITestResult>(); var element = webDriver.GetElementWhenRendered(x => x.FindElement(By.Id(ResultsElement))); if (element != null) { var testOutputs = webDriver.FindElements(By.XPath("//*[contains(@id,'test-output')]")); testResults.AddRange(testOutputs.Select(GetTestResultFromTestOutPut)); } return testResults; }
public static IList<IWebElement> GetElements(By by, IWebDriver driver) { try { WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeout)); IWebElement element = wait.Until<IWebElement>(ExpectedConditions.ElementExists(by)); wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0")); return driver.FindElements(by); } catch(Exception) { return null; } }
public override void Execute(IWebDriver driver, dynamic context) { var resolvedSelector = Test.ResolveMacros(Selector); IList<IWebElement> elements; if (Wait) { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(WaitTimeout == 0 ? 5000 : WaitTimeout)); var element = wait.Until(d => d.FindElement(By.CssSelector(resolvedSelector))); } elements = driver.FindElements(By.CssSelector(resolvedSelector)); Execute(driver, context, elements); }
public IEnumerable<IWebElement> FindMany(IWebDriver webDriver, string elementSelector, int seconds = 10) { try { var cssSelector = By.CssSelector(elementSelector); var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(seconds)); wait.Until(ExpectedConditions.ElementExists(cssSelector)); return webDriver.FindElements(cssSelector); } catch (Exception ex) { throw new ElementNotFoundException(elementSelector, seconds); } }
public void PopulateValidProjectSettings(IWebDriver driverInstance) { IWebElement input = driverInstance.FindElement(NgBy.Input("ProjectWizardController.project.name")); IWebElement textarea = driverInstance.FindElement(By.Id("txtDescription")); ICollection<IWebElement> radioGroup = driverInstance.FindElements(NgBy.Input("ProjectWizardController.project.docSource")); IWebElement checkbox = driverInstance.FindElement(By.Id("checkboxes-0")); input.Clear(); input.SendKeys("TestProject"); textarea.Clear(); textarea.SendKeys("Sample_Description_Text1#"); radioGroup.ElementAt(0).Click(); }
protected internal BaseInboxPage(IWebDriver driver) { _driver = driver; _periodDropdowns = _driver.FindElements(By.XPath(Constants.BaseMailbox.XP.PERIOD_DD)); _statusDropdowns = _driver.FindElements(By.XPath(Constants.BaseMailbox.XP.STATUS_DD)); Thread.Sleep(500); PeriodDropdown = _periodDropdowns.First(); StatusDropdown = _statusDropdowns.First(); QuickSearchTextbox = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.QS_TEXTBOX); QuickSearchBtn = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.QS_BTN); ResultGrid = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.RSLT_GRID); PrintBtn = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.PRINT_BTN); MarkProcBtn = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.MP_BTN); ASButton = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.AS_LINK); ActionsBtn = HelperMethods.FindElement(_driver, Constants.SearchType.ID, Constants.BaseMailbox.ID.ACTIONS_BTN); if (!_driver.Url.Contains("Mailbox")) { _logger.Fatal(" > Mailbox navigation [FAILED]"); _logger.Fatal("-- TEST FAILURE @ URL: '" + _driver.Url + "' --"); BaseDriverTest.TakeScreenshot("screenshot"); } }
public static bool IsElementDisplayed(IWebDriver driver, By element) { if (driver.FindElements(element).Count > 0) { if (driver.FindElement(element).Displayed) return true; else return false; } else { return false; } }
public IList<string> GetAllIdS(IWebDriver driver) { IList<IWebElement> ids = driver.FindElements(By.XPath("/html/body/div/div/descendant::div")); IList<string> idList = new List<string>(); string convert; foreach (IWebElement _ids in ids) { _ids.GetAttribute("id"); convert = _ids.ToString(); idList.Add(convert); } return idList; }
public void Login() { ChromeOptions options = new ChromeOptions(); options.AddArgument("--no-sandbox"); options.AddArgument("--disable-extensions"); options.AddArgument("--start-maximized"); driver = new ChromeDriver(options); driver.Navigate().GoToUrl("http://www.qa.way2automation.com"); driver.FindElement(By.CssSelector("#load_form > h3")); driver.FindElement(By.CssSelector("#load_form > div > div.span_3_of_4 > p > a[href='#login']")).Click(); driver.FindElement(By.CssSelector("#load_form > fieldset:nth-child(5) > input[name='username']")).SendKeys("j2bwebdriver"); driver.FindElement(By.CssSelector("#load_form > fieldset:nth-child(6) > input[name='password']")).SendKeys("j2bwebdriver"); driver.FindElements(By.CssSelector("#load_form > div > div.span_1_of_4 > input"))[1].Submit(); Thread.Sleep(1000); }
private List<Cinema> scrapOnePageCinema(IWebDriver driver) { var cinemaList = new List<Cinema>(); var cinemas = driver.FindElements(By.CssSelector(".theater")); foreach (var cinema in cinemas) { var currCinemaName = cinema.FindElement(By.CssSelector("a[id^='link_1_theater_']")).Text; var currCinemaAddress = cinema.FindElement(By.CssSelector(".info")).Text; cinemaList.Add(new Cinema() { CinemaName = currCinemaName, CinemaAddress = currCinemaAddress }); } return cinemaList; }
/// <summary> /// Handles the command. /// </summary> /// <param name="driver">The driver used to execute the command.</param> /// <param name="locator">The first parameter to the command.</param> /// <param name="value">The second parameter to the command.</param> /// <returns>The result of the command.</returns> protected override object HandleSeleneseCommand(IWebDriver driver, string locator, string value) { ReadOnlyCollection<IWebElement> allInputs = driver.FindElements(By.XPath("//input")); List<string> ids = new List<string>(); foreach (IWebElement input in allInputs) { string type = input.GetAttribute("type").ToUpperInvariant(); if (type == "TEXT") { ids.Add(input.GetAttribute("id")); } } return ids.ToArray(); }
public void Search(IWebDriver driver) { string names = null; driver.FindElement(By.CssSelector("input.ui-input-text.ui-body-d")).SendKeys("card"); driver.FindElement(By.CssSelector("input.ui-input-text.ui-body-d")).SendKeys(Keys.Enter); var productnames = driver.FindElements(By.CssSelector("[itemprop='name']")); for (var i = 0; i < 32; i++) { var name = productnames[i].Text; names = name + "\n" + names; } if (names == null) return; var charArray = names.ToCharArray(); Array.Reverse(charArray); }
public ReadOnlyCollection <IWebElement> FindElements(By by) { return(_webDriver.FindElements(by)); }
private IWebElement GetOneWayLabel() => driver.FindElements(By.ClassName("radio-inline"))[1];
public static IWebElement GetInnerElement(this IWebDriver driver, string tagName, string attrName, string attrValue) { return(driver?.FindElements(By.TagName(tagName)).FirstOrDefault(tag => tag.GetAttribute(attrName) == attrValue)); }
public void TestJustEat() { VisualGridRunner runner = new VisualGridRunner(10); IWebDriver driver = SeleniumUtils.CreateChromeDriver(); Eyes eyes = InitEyesWithLogger(runner, verbose: true, writeResources: true); //ConfigureSingleBrowser(eyes); ConfigureMultipleBrowsers(eyes); OpenEyes(driver, "https://www.just-eat.co.uk/", eyes, 1000, 700); try { //Close the cookie notification footer driver.FindElement(By.XPath("//*[@data-test-id='cookieBanner-close-button']")).Click(); IJavaScriptExecutor js = (IJavaScriptExecutor)driver; //Driver for Uber ad shows randomly. Remove this element so it doesn't affect our tests //IWebElement uberContainer = _driver.FindElementByClassName("ex1140 l-container"); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); //IWebElement element = wait.Until(ExpectedConditions.ElementExists(By.CssSelector("div.ex1140.l-container"))); js.ExecuteScript("var e = document.querySelector('div.ex1140.l-container'); if (e) e.hidden = true;"); eyes.CheckWindow("Homepage"); eyes.CheckWindow("another test"); //Search by Postal Code driver.FindElement(By.Name("postcode")).SendKeys("EC4M7RA"); driver.FindElement(By.XPath("//button[@data-test-id='find-restaurants-button']")).Click(); //Deal with time of day issues -- Sometimes it asks if you want take away driver.FindElement(By.ClassName("closeButton")).Click(); //Narrow the search to just first in the list (helps when running before the restaurant is open wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div.c-searchFilterSection-filterList span:nth-child(1)"))).Click(); wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div[data-test-id=searchresults] section:nth-child(1)"))).Click(); //Open the Show More link IList <IWebElement> showMoreLink = driver.FindElements(By.Id("showMoreText")); if (showMoreLink.Count > 0) { Actions actions = new Actions(driver); actions.MoveToElement(showMoreLink[0]).Click().Perform(); } eyes.CheckWindow(); eyes.CheckRegion(By.ClassName("menuDescription"), "Menu Description"); //eyes.ForceFullPageScreenshot = false; //Check the top Food Allergy link driver.FindElement(By.XPath("//div[@id='basket']//button[contains(text(), 'If you or someone')]")).Click(); eyes.CheckWindow("last"); eyes.CheckRegion(By.XPath("//div[@data-ft='allergenModalDefault']"), "Food Allergy - Top", false); driver.FindElement(By.XPath("//button[text()='Close']")).Click(); //Scroll to the bottom of the page to check the second Food Allergy link js.ExecuteScript("window.scrollTo(0, document.body.scrollHeight)"); //retryingFindClick(By.XPath("//div[@id='menu']//button[contains(text(), 'If you or someone')]")); //eyes.CheckElement(By.XPath("//div[@data-ft='allergenModalDefault']"), "Food Allergy - Bottom"); //eyes.CheckRegion(By.XPath("//div[@data-ft='allergenModalDefault']"), "Food Allergy - Bottom", false); //eyes.CheckWindow("Food Allergy - Bottom"); //driver.FindElement(By.XPath("//button[text()='Close']")).Click();/**/ eyes.CloseAsync(); runner.GetAllTestResults(); } finally { eyes.Abort(); driver.Quit(); } }
public async Task <bool> Login(long simCardNumber, bool isFromSimcard) { try { var sim_ = await SimcardBussines.GetAsync(simCardNumber); if (isFromSimcard) { _driver = Utility.RefreshDriver(clsAdvertise.IsSilent); var simBusiness = await Utility.CheckToken(simCardNumber, AdvertiseType.Sheypoor); // در صورتیکه توکن قبلا ثبت شده باشد لاگین می کند if (!simBusiness.HasError) { // token = _driver.Manage().Cookies.GetCookieNamed("ts").ToString().Substring(3, 32); _driver.Navigate().GoToUrl("https://www.sheypoor.com"); _driver.Manage().Cookies.DeleteCookieNamed("ts"); var newToken = new OpenQA.Selenium.Cookie("ts", simBusiness.value); _driver.Manage().Cookies.AddCookie(newToken); _driver.Navigate().GoToUrl("https://www.sheypoor.com/session/myListings"); var linksElements = _driver.FindElements(By.TagName("a")).ToList(); foreach (var link in linksElements) { if (link?.GetAttribute("href") == null || !link.GetAttribute("href").Contains("logout")) { continue; } _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); return(true); } } //اگر قبلا توکن نداشته و یا توکن اشتباه باشد وارد صفحه دریافت کد تائید لاگین می شود _driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 2, 0); _driver.Navigate().GoToUrl("https://www.sheypoor.com/session/myListings"); //var all = _driver.Manage().Cookies.AllCookies; if (_driver.FindElements(By.Id("username")).Count > 0) { _driver.FindElement(By.Id("username")).SendKeys(simCardNumber + "\n"); } //انتظار برای لاگین شدن int repeat = 0; //حدود 120 ثانیه فرصت لاگین دارد while (repeat < 20) { //تا زمانی که لاگین اوکی نشده باشد این حلقه تکرار می شود var badGateWay = _driver.FindElements(By.TagName("h1")) .Any(q => q.Text == "502 Bad Gateway" || q.Text == "Error 503 Service Unavailable"); if (badGateWay) { return(false); } var message = $@"مالک: {sim_.Owner} \r\nشماره: {simCardNumber} \r\nلطفا لاگین نمائید "; _driver.ExecuteJavaScript($"alert('{message}');"); //Wait(); await Utility.Wait(5); try { _driver.SwitchTo().Alert().Accept(); await Utility.Wait(10); repeat++; } catch { await Utility.Wait(15); } var linksElements = _driver?.FindElements(By.TagName("a")).ToList() ?? null; AdvTokenBussines advToken = null; foreach (var link in linksElements) { if (link?.GetAttribute("href") == null || !link.GetAttribute("href").Contains("logout")) { continue; } advToken = await AdvTokenBussines.GetTokenAsync(simCardNumber, AdvertiseType.Sheypoor); var token = _driver.Manage().Cookies.GetCookieNamed("ts").ToString().Substring(3, 32); if (advToken != null) { advToken.Token = token; } else { advToken = new AdvTokenBussines() { Type = AdvertiseType.Sheypoor, Token = token, Number = simCardNumber, Guid = Guid.NewGuid(), } }; await advToken.SaveAsync(); _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); return(true); } } var linksElements1 = _driver?.FindElements(By.TagName("a")).FirstOrDefault(q => q.Text == "خروج") ?? null; if (linksElements1 == null) { var msg = $@"فرصت لاگین کردن به اتمام رسید. لطفا دقایقی بعد مجددا امتحان نمایید"; _driver.ExecuteJavaScript($"alert('{msg}');"); _driver.SwitchTo().Alert().Accept(); await Utility.Wait(3); } await Utility.Wait(); } else { _driver = Utility.RefreshDriver(clsAdvertise.IsSilent); var simBusiness = await Utility.CheckToken(simCardNumber, AdvertiseType.Sheypoor); // در صورتیکه توکن قبلا ثبت شده باشد لاگین می کند if (!simBusiness.HasError) { // token = _driver.Manage().Cookies.GetCookieNamed("ts").ToString().Substring(3, 32); _driver.Navigate().GoToUrl("https://www.sheypoor.com"); _driver.Manage().Cookies.DeleteCookieNamed("ts"); var newToken = new OpenQA.Selenium.Cookie("ts", simBusiness.value); _driver.Manage().Cookies.AddCookie(newToken); _driver.Navigate().GoToUrl("https://www.sheypoor.com/session/myListings"); var linksElements = _driver.FindElements(By.TagName("a")).ToList(); foreach (var link in linksElements) { if (link?.GetAttribute("href") == null || !link.GetAttribute("href").Contains("logout")) { continue; } _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); return(true); } } _driver.Navigate().GoToUrl("https://www.sheypoor.com/session/myListings"); //انتظار برای لاگین شدن int repeat = 0; //حدود 120 ثانیه فرصت لاگین دارد while (repeat < 5) { //تا زمانی که لاگین اوکی نشده باشد این حلقه تکرار می شود var badGateWay = _driver.FindElements(By.TagName("h1")) .Any(q => q.Text == "502 Bad Gateway" || q.Text == "Error 503 Service Unavailable"); if (!badGateWay) { return(false); } var message = $@"مالک: {sim_.Owner} \r\nشماره: {simCardNumber} \r\nلطفا لاگین نمائید "; _driver.ExecuteJavaScript($"alert('{message}');"); //Wait(); await Utility.Wait(2); try { _driver.SwitchTo().Alert().Accept(); await Utility.Wait(1); repeat++; } catch { await Utility.Wait(15); } var linksElements = _driver?.FindElements(By.TagName("a")).ToList() ?? null; AdvTokenBussines advToken = null; foreach (var link in linksElements) { if (link?.GetAttribute("href") == null || !link.GetAttribute("href").Contains("logout")) { continue; } var token = _driver.Manage().Cookies.GetCookieNamed("ts").ToString().Substring(3, 32); advToken = await AdvTokenBussines.GetTokenAsync(simCardNumber, AdvertiseType.Sheypoor); if (advToken != null) { advToken.Token = token; } else { advToken = new AdvTokenBussines() { Type = AdvertiseType.Sheypoor, Token = token, Number = simCardNumber, Guid = Guid.NewGuid(), } }; } await advToken?.SaveAsync(); _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); return(true); } } await Utility.Wait(); TelegramSender.GetChatLog_bot().Send( $"#نداشتن_توکن \r\n سیستم مرجع: {await Utilities.GetNetworkIpAddress()} \r\n شماره {simCardNumber} به مالکیت {sim_.Owner} توکن ارسال آگهی شیپور داشته، اما منقضی شده و موفق به لاگین نشد " + $"\r\n به همین سبب توکن شیپور این شماره از دیتابیس حذف خواهد شد " + $"\r\n لطفا نسبت به دریافت مجدد توکن اقدام گردد."); var advTokens = await AdvTokenBussines.GetTokenAsync(simCardNumber, AdvertiseType.Sheypoor); await advTokens?.RemoveAsync(); return(false); } catch (WebException) { return(false); } catch (Exception ex) { if (ex.Source != "WebDriver") { WebErrorLog.ErrorInstence.StartErrorLog(ex); } return(false); } }
public IList <IWebElement> _deptNames() { return(_driver.FindElements(By.XPath(".//*[@id='organizationDocumentsDiv']/div/a/label"))); }
public static List <string> GetAllLinksInPage(IWebDriver driver) { return(driver.FindElements(By.TagName("a")).Select(link => link.GetAttribute("href")).ToList()); }
private Boolean PreparaPesquisa() { try { driver.Navigate().GoToUrl("http://smap14.mda.gov.br/extratodap/PesquisarDAP"); IWebElement a = driver.FindElement(By.XPath("//*[contains(@onclick, 'Fisica')]")); a.Click(); Thread.Sleep(2500); if (!AguardaElemento(TipoElemento.css, "[href*='#Municipio']", 20)) { /* * * Caso necessário pode fazer todo o código em um loop que da um return false e na chamada caso venha falso reinicia o bot * */ } IWebElement b = driver.FindElement(By.CssSelector("[href*='#Municipio']")); b.Click(); Thread.Sleep(1500); if (!AguardaElemento(TipoElemento.id, "ddlUF", 20)) { //return false; } IWebElement c = driver.FindElement(By.Id("ddlUF")); SelectElement seleC = new SelectElement(c); seleC.SelectByValue("42"); Thread.Sleep(1500); if (!AguardaElemento(TipoElemento.id, "ddlMunicipio", 20)) { //return false; } IWebElement d = driver.FindElement(By.Id("ddlMunicipio")); SelectElement seleD = new SelectElement(d); seleD.SelectByValue("4201208"); Thread.Sleep(1500); GetImagCaptcha(); Thread.Sleep(1500); if (!AguardaElemento(TipoElemento.id, "btnPesquisarMunicipio", 20)) { //return false; } IList <IWebElement> botoes = driver.FindElements(By.Id("btnPesquisarMunicipio")); IWebElement e = driver.FindElement(By.Id("btnPesquisarMunicipio")); string script = botoes[2].GetAttribute("onclick"); driver.ExecuteJavaScript <object>(script); //e.Click(); Thread.Sleep(3500); if (!AguardaElemento(TipoElemento.id, "gridPessoaFisica", 20, true)) { //return false; } IList <IWebElement> f = driver.FindElement(By.Id("gridPessoaFisica")).FindElements(By.TagName("a")); Thread.Sleep(2500); foreach (IWebElement link in f) { string onclick = link.GetAttribute("onclick"); driver.ExecuteJavaScript <object>(onclick); break; } Thread.Sleep(2500); return(true); } catch (Exception e) { return(false); } }
public static ReadOnlyCollection <IWebElement> FindElements(this IWebDriver driver, ElementLocator locator, params object[] parameters) { locator = locator.Format(parameters); new WebDriverWait(driver, TimeSpan.FromSeconds(Wait)).Until(drv => driver.FindElements(locator.ToBy(locator)).Count > 0); return(driver.FindElements(locator.ToBy(locator))); }
internal static ReadOnlyCollection <IWebElement> FindByXpath(string xpath) { return(_driver.FindElements(By.XPath(xpath))); }
public void Start() { IJavaScriptExecutor js = (IJavaScriptExecutor)driver; for (int j = 0; j < numberOfTabs; j++) { js.ExecuteScript("window.open()"); } tabs = new List <String>(driver.WindowHandles); used = new List <string>();; List <IWebElement> elements; for (int j = 0; j < tabs.Count - 1; j++) { driver.SwitchTo().Window(tabs[j + 1]); driver.Navigate().GoToUrl(simple); used.Add("empty"); } while (true) { driver.SwitchTo().Window(tabs[0]); Thread.Sleep(10000); List <Tab> listOfTabs = new List <Tab>(); elements = driver.FindElements(By.XPath("//a[@class='mod-link']")).ToList(); Console.WriteLine(elements.Count + " - links"); for (int i = 0; i < elements.Count; i++) { Tab tab = new Tab(); tab.id = elements[i].GetAttribute("data-event-or-meeting-id"); tab.url = elements[i].GetAttribute("href"); listOfTabs.Add(tab); } elements = driver.FindElements(By.XPath("//a[@class='mod-link']/event-line/section/ul[3]")).ToList(); Console.WriteLine(elements.Count + " - matched"); for (int i = 0; i < elements.Count; i++) { int sum = 0; string s = elements[i].GetAttribute("title"); foreach (char x in s) { if (x >= '0' && x <= '9') { sum = sum * 10 + x - '0'; } } listOfTabs[i].matched = sum; } elements = driver.FindElements(By.XPath("//data-bf-livescores-time-elapsed/ng-include/div/div/div")).ToList(); Console.WriteLine(elements.Count + " - inPlay"); for (int i = 0; i < Math.Min(elements.Count, listOfTabs.Count()); i++) { if (elements[i].Text != "END") { listOfTabs[i].inPlay = true; } } if (toDelete.Count > 0) { Delete(); } Console.WriteLine("STARTTTTT"); Console.WriteLine(listOfTabs.Count + " - tabs"); Console.WriteLine(used.Count + " - used"); int ttmp = 0; for (int i = 0; i < used.Count(); i++) { if (used[i] == "empty") { ttmp++; } } Console.WriteLine("TTMP: " + ttmp); int cnt = 0; for (int i = 0; i < listOfTabs.Count(); i++) { if (listOfTabs[i].inPlay && listOfTabs[i].matched > 6000) { cnt++; } } Console.WriteLine(cnt + " - cnt"); for (int i = cnt / 30; i < listOfTabs.Count; i++) { if (listOfTabs[i].inPlay && listOfTabs[i].matched > 6000) { for (int j = 0; j < used.Count; j++) { if (used[j] == "empty" && !usedLinks.Contains(listOfTabs[i].id)) { Console.WriteLine(listOfTabs[i].id); used[j] = listOfTabs[i].id; usedLinks.Add(listOfTabs[i].id); driver.SwitchTo().Window(tabs[j + 1]); driver.Navigate().GoToUrl(listOfTabs[i].url); break; } } } } for (int i = 1; i < tabs.Count; i++) { driver.SwitchTo().Window(tabs[i]); Thread.Sleep(5000); } Thread.Sleep(30000); } }
public static List <Investimento> Sync() { var class_name = "Inflação"; var investimentos = new List <Investimento>(); IWebDriver driver = null; var cultureBR = new CultureInfo("pt-BR"); var ano_max = 2007; try { UI.StartChrome(ref driver); driver.Url = "https://www.cut.org.br/indicadores/inflacao-mensal-ipca"; UI.WaitPageLoad(driver); UI.Wait(3); UI.ClickWhenDisplayed(driver, By.XPath("//div[@data-filter='max']")); UI.Wait(3); IList <IWebElement> lines = driver.FindElements(By.XPath("//div[@class='line']")); foreach (var line in lines) { var arr = line.Text.Replace("\r\n", "|").Split(Convert.ToChar("|")); if (arr.Length == 3) { var mes_ano = arr[0].Split(Convert.ToChar(" ")); if (mes_ano.Length == 2) { int ano; bool isNumeric = int.TryParse(mes_ano[1], out ano); if (isNumeric && ano >= ano_max) { var mes = DateTime.ParseExact(mes_ano[0], "MMMM", new CultureInfo("pt-BR")).Month; var investimento = new Investimento(); investimento.tipo = "Público"; investimento.nome = "Inflação"; investimento.mes = new DateTime(ano, mes, 1); investimento.valor = Convert.ToDouble(arr[1]); investimentos.Add(investimento); } } } } } catch (Exception ex) { UI.SaveHtmlAndPrint(driver, class_name, ex); throw ex; } finally { if (driver != null) { try { driver.Close(); } catch { } driver.Quit(); driver.Dispose(); driver = null; } } // Retorna os registros return(investimentos); }
public async Task <bool> Login(List <long> simCardNumber) { var monitor = new PerfMonitor(); try { foreach (var item in simCardNumber) { Utility.CloseAllChromeWindows(); await GetInstance(); _driver = Utility.RefreshDriver(_driver); var simBusiness = await AdvTokensBusiness.GetToken(item, AdvertiseType.NiazmandyHa); var simcard = await SimCardBusiness.GetAsync(item); var token = simBusiness?.Token; _driver.Navigate().GoToUrl("https://niazmandyha.ir/panel/ads"); // در صورتیکه توکن قبلا ثبت شده باشد لاگین می کند if (!string.IsNullOrEmpty(token)) { var cooc = _driver.Manage().Cookies.AllCookies; if (cooc.Count == 3) { _driver.Manage().Cookies.DeleteCookieNamed(CookieStore.NiazmandyHaCookieName.Value); } _driver.Navigate().Refresh(); var a = new OpenQA.Selenium.Cookie(CookieStore.NiazmandyHaCookieName.Value, token); _driver.Manage().Cookies.AddCookie(a); _driver.Navigate().Refresh(); _driver.Navigate().GoToUrl("https://niazmandyha.ir/panel/ads"); var linksElements = _driver.FindElements(By.ClassName("black")) .FirstOrDefault(q => q.Text == "خروج"); if (linksElements != null) { _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); continue; } _driver.FindElement(By.Id("username")).SendKeys(simcard.UserName); _driver.FindElement(By.Id("password")).SendKeys("0" + item + '\n'); var linksElement = _driver.FindElements(By.ClassName("black")) .FirstOrDefault(q => q.Text == "خروج"); if (linksElement != null) { token = _driver.Manage().Cookies.AllCookies.LastOrDefault()?.Value ?? null; simBusiness.Token = token; await simBusiness?.SaveAsync(); _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); continue; } } //اگر قبلا توکن نداشته و یا توکن اشتباه باشد وارد صفحه ثبت نام می شود _driver.Manage().Timeouts().PageLoad = new TimeSpan(0, 2, 0); _driver.FindElements(By.TagName("span")) .FirstOrDefault(q => q.Text == "عضویت در نیازمندی ها")?.Click(); _driver.FindElement(By.Id("name")).SendKeys(simcard.OwnerName); _driver.FindElement(By.Id("tel")).SendKeys("0" + item); _driver.FindElement(By.Id("email")).SendKeys(simcard.UserName + "@Yahoo.com"); _driver.FindElement(By.Id("username")).SendKeys(simcard.UserName); _driver.FindElement(By.Id("password")).SendKeys("0" + item); _driver.FindElements(By.TagName("button")).FirstOrDefault(q => q.Text == "ثبت نام")?.Click(); await Utility.Wait(); var counter = 0; while (_driver.Url == "https://niazmandyha.ir/login" || _driver.Url == "https://niazmandyha.ir/register") { //تا زمانی که لاگین اوکی نشده باشد این حلقه تکرار می شود counter++; if (counter >= 60) { break; } var name = await SimCardBusiness.GetOwnerNameAsync(item); var message = $@"مالک: {name} \r\nشماره: {item} \r\nلطفا لاگین نمائید "; _driver.ExecuteJavaScript($"alert('{message}');"); await Utility.Wait(3); try { _driver.SwitchTo().Alert().Accept(); await Utility.Wait(3); } catch { await Utility.Wait(15); } var linksElements = _driver.FindElements(By.ClassName("black")) .FirstOrDefault(q => q.Text == "خروج"); if (linksElements == null) { continue; } token = _driver.Manage().Cookies.AllCookies.LastOrDefault()?.Value ?? null; if (string.IsNullOrEmpty(token)) { continue; } if (simBusiness != null) { simBusiness.Token = token; } else { simBusiness = new AdvTokensBusiness { Guid = Guid.NewGuid(), Token = token, Modified = DateTime.Now, Number = item, Type = AdvertiseType.NiazmandyHa }; } await simBusiness?.SaveAsync(); _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); Utility.CloseAllChromeWindows(); continue; } if (_driver.Url != "https://niazmandyha.ir/panel") { return(false); } token = _driver.Manage().Cookies.AllCookies.LastOrDefault()?.Value ?? null; if (simBusiness != null) { simBusiness.Token = token; } else { simBusiness = new AdvTokensBusiness { Guid = Guid.NewGuid(), Token = token, Modified = DateTime.Now, Number = item, Type = AdvertiseType.NiazmandyHa }; } await simBusiness?.SaveAsync(); _driver.ExecuteJavaScript(@"alert('لاگین انجام شد');"); await Utility.Wait(); _driver.SwitchTo().Alert().Accept(); if (counter < 60) { return(true); } var linksElements1 = _driver?.FindElements(By.ClassName("black")) .FirstOrDefault(q => q.Text == "خروج") ?? null; if (linksElements1 == null) { var msg = $@"فرصت لاگین کردن به اتمام رسید. لطفا دقایقی بعد مجددا امتحان نمایید"; _driver.ExecuteJavaScript($"alert('{msg}');"); _driver.SwitchTo().Alert().Accept(); await Utility.Wait(3); } _driver.Navigate().GoToUrl("https://niazmandyha.ir"); await Utility.Wait(); simBusiness.Token = null; await simBusiness.SaveAsync(); } return(false); } catch (WebException) { return(false); } catch (Exception ex) { if (ex.Source != "WebDriver") { WebErrorLog.ErrorLogInstance.StartLog(ex); } return(false); } finally { monitor.Dispose(); } }
public IReadOnlyList <IWebElement> GetAllEmployees() { return(driver.FindElements(By.XPath("//div[@class='content']/h2"))); }
public string AccesRegisterAmbassador(IWebDriver driver) { driver.FindElements(By.ClassName("nav-item"))[1].Click(); return(driver.Url); }
public static bool InvisibilityOfRefreshMarker(this IWebDriver d) { return(d.FindElements(By.ClassName(RefreshMarker)).Any()); }
public int RegisterEmptyAmbassador(IWebDriver driver) { driver.FindElements(By.ClassName("nav-item"))[1].Click(); driver.FindElement(By.Id("submitButton")).Click(); return(driver.FindElements(By.ClassName("text-danger")).Count); }
public void pages_can_be_navigated_by_clicking_on_links() { // selecting and clicking on image, taking us to detail page Thread.Sleep(SlowDownTwo); IWebElement parkLink = webDriver.FindElement(By.XPath("//*[@id=\"x1\"]/div[1]/a/img")); parkLink.Click(); Thread.Sleep(SlowDownTwo); Assert.IsNotNull(parkLink); IWebElement detailH2 = webDriver.FindElement(By.TagName("h2")); Assert.AreEqual("Detail", detailH2.Text); // on detail page scrolling down to quick facts IWebElement scrollToFacts = webDriver.FindElement(By.ClassName("facts-headline")); Actions scrollDown = new Actions(webDriver); scrollDown.MoveToElement(scrollToFacts); scrollDown.Perform(); Thread.Sleep(SlowDownTwo); Assert.AreEqual("Quick Facts", scrollToFacts.Text); // scrolling down to weather from quick facts IWebElement scrollToWeather = webDriver.FindElement(By.ClassName("tile-weather-small")); scrollDown.MoveToElement(scrollToWeather); scrollDown.Perform(); Thread.Sleep(SlowDownTwo); // going back to home from button home in nav bar IWebElement homeLink = webDriver.FindElement(By.XPath("/html/body/nav/div/div[2]/ul/li[1]/a")); homeLink.Click(); Thread.Sleep(SlowDownTwo); // going to survey from home via survey button in nav bar IWebElement surveyLink = webDriver.FindElement(By.XPath("/html/body/nav/div/div[2]/ul/li[2]/a")); surveyLink.Click(); Thread.Sleep(SlowDownTwo); // enter email in survey IWebElement surveyEmail = webDriver.FindElement(By.XPath("//*[@id=\"email\"]")); surveyEmail.SendKeys("*****@*****.**"); Thread.Sleep(SlowDownTwo); // clicking on park drop down IWebElement parkDrop = webDriver.FindElement(By.XPath("//*[@id=\"park-selection\"]")); parkDrop.Click(); Thread.Sleep(SlowDownOne); // selecting park from dropdown SelectElement parkSelection = new SelectElement(webDriver.FindElement(By.Id("park-selection"))); parkSelection.SelectByText("Glacier National Park"); Thread.Sleep(SlowDownOne); // clicking on state dropdown IWebElement residenceDrop = webDriver.FindElement(By.XPath("//*[@id=\"state-selection\"]")); residenceDrop.Click(); Thread.Sleep(SlowDownOne); // selecting state from dropdown SelectElement residenceSelection = new SelectElement(webDriver.FindElement(By.Id("state-selection"))); residenceSelection.SelectByText("Pennsylvania"); Thread.Sleep(SlowDownTwo); // Assert - testing dropdown for activity level List <string> activityDropDown = new List <string>() { "Inactive", "Sedentary", "Active", "Extremely Active" }; IList <IWebElement> activityDropDownList = webDriver.FindElements(By.CssSelector("#activity-selection")); foreach (IWebElement i in activityDropDownList) { foreach (string s in activityDropDown) { Assert.AreEqual(true, i.Text.Contains(s)); } } // clicking on activity dropdown IWebElement activityDrop = webDriver.FindElement(By.XPath("//*[@id=\"activity-selection\"]")); activityDrop.Click(); Thread.Sleep(SlowDownOne); // selecting activity level from dropdown SelectElement activitySelection = new SelectElement(webDriver.FindElement(By.Id("activity-selection"))); activitySelection.SelectByText("Extremely Active"); Thread.Sleep(SlowDownTwo); // clicking submit button, going to surveyResults page IWebElement submitButton = webDriver.FindElement(By.ClassName("submit-button")); submitButton.Click(); Thread.Sleep(SlowDownTwo); // going to home page again from surveyResults page via home button in nav bar IWebElement homeLinkReturn = webDriver.FindElement(By.XPath("/html/body/nav/div/div[2]/ul/li[1]/a")); homeLinkReturn.Click(); Thread.Sleep(SlowDownTwo); // navigating to google.com webDriver.Navigate().GoToUrl("http://google.com"); Thread.Sleep(SlowDownTwo); // going back to our site from google webDriver.Navigate().GoToUrl(Helper.URL); Thread.Sleep(SlowDownTwo); }
private IEnumerable <IWebElement> GetAllChoiceDivs() { return(driver.FindElements(By.XPath(choices))); }
List <IWebElement> GetProductItemsList() { return(driver.FindElements(By.CssSelector(".content a.link")).ToList()); }
public void TVWeb_001_VerifyBottomBar() { try { IWebElement backToTop; IJavaScriptExecutor executor; String myCommunityURL, faceBookURL, twitterURL, linkedinURL, youTubeURL, myCommunityStatus, facebookStatus, twitterStatus, linkedinStatus, youTubeStatus, myIETHeader, IETTvHelp, TvAccType, othIETSites, abtLinksURL, othLinksURL, bottomFooterURL, abtLinkStatus, othLinkStatus, IEThelpURL, IEThelpStatus, IETAccTypeURL, IETAccTypeStatus, bottomLinkStatus, copyRightText; IList <IWebElement> myCommunityLinks, myCommunity, facebook, twitter, linkedin, youTube, footerSection, footerFourSections, abtIET, abtHelp, abtAccType, abtOthSites, bottomFooter, bottomFooterList; String[] arrAbtIET = { "Vision, mission & values", "People", "Our offices & venues", "Savoy Place upgrade", "Working at the IET" }; String[] arrIETHelp = { "FAQ", "Institution", "Technical requirements", "Contact", "Corporate", "Forgot password", "Delegate / Speaker access code" }; String[] arrAccType = { "Institution", "Members", "Visitor", "Corporate", "Individual" }; String[] arrOthSites = { "The IET", "E&T Jobs", "E&T Magazine", "", "IET Connect", "IET Digital Library", "IET Electrical", "IET Faraday", "IET Venues" }; String[] arrBottomFooter = { "Cookies", "Privacy Statement", "Accessibility", "Legal Notices", "T&C" }; int ScrollTop, cntFooterSections, cntGlobal = 0; WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(60)); wait.Until(ExpectedConditions.ElementExists(By.ClassName(or.readingXMLFile("BottomBar", "overLaySpinner", "TVWebPortalOR.xml")))); Thread.Sleep(2000); Boolean resScrollDown = uf.scrollDown(driver); log.Info("Scroll Down Result=" + resScrollDown + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Thread.Sleep(5000); // Verify scroll down is performed Assert.AreEqual(true, resScrollDown); backToTop = driver.FindElement(By.Id(or.readingXMLFile("BottomBar", "backToTop", "TVWebPortalOR.xml"))).FindElement(By.TagName("a")); // Verify Back to Top anchor is present Assert.AreEqual("Click to Go Top", backToTop.GetAttribute("title").ToString()); // Click on Back to Top anchor executor = (IJavaScriptExecutor)driver; executor.ExecuteScript("arguments[0].click();", backToTop); Thread.Sleep(2000); ScrollTop = uf.getScrollTop(driver); // Verify Back to Top functionality Assert.AreEqual(0, ScrollTop); Thread.Sleep(2000); // Once again scroll down for link verification uf.scrollDown(driver); Thread.Sleep(2000); //////// Verify My Community Icon Presence and Status /////// myCommunityLinks = driver.FindElement(By.ClassName(or.readingXMLFile("BottomBar", "myCommunityLinks", "TVWebPortalOR.xml"))).FindElements(By.TagName("li")); log.Info("Total icon List" + myCommunityLinks.Count + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify Total No. of My community icons Assert.AreEqual(5, myCommunityLinks.Count); // Verify MyCommunity section is present myCommunity = myCommunityLinks.ElementAt(0).FindElements(By.TagName("a")); Assert.AreEqual(1, myCommunity.Count); myCommunityURL = myCommunity.ElementAt(0).GetAttribute("href").ToString(); log.Info("My Community URL:" + myCommunityURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify MyCommunity URL Assert.AreEqual("http://mycommunity.theiet.org/?origin=foot-social", myCommunityURL); // Verify MyCommunity Request Status myCommunityStatus = uf.getStatusCode(new Uri(myCommunityURL.ToString())); Assert.AreEqual("OK", myCommunityStatus); // Verify MyCommunity icon title text Assert.AreEqual("My Community icon", myCommunity.ElementAt(0).FindElement(By.TagName("img")).GetAttribute("title").ToString()); // Verify MyCommunity text Assert.AreEqual("MyCommunity", myCommunity.ElementAt(0).FindElement(By.TagName("span")).Text.ToString()); // Verify Facebook icon is present and it's status facebook = myCommunityLinks.ElementAt(1).FindElements(By.TagName("a")); faceBookURL = facebook.ElementAt(0).GetAttribute("href").ToString(); log.Info("Facebook URL:" + faceBookURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify Facebook URL Assert.AreEqual("http://www.theiet.org/policy/media/follow/facebook.cfm?origin=foot-social", faceBookURL); // Verify Facebook Request Status facebookStatus = uf.getStatusCode(new Uri(faceBookURL.ToString())); Assert.AreEqual("OK", facebookStatus); // Verify Facebook icon title text Assert.AreEqual("Facebook icon", facebook.ElementAt(0).FindElement(By.TagName("img")).GetAttribute("title").ToString()); // Verify Twitter icon is present and it's status twitter = myCommunityLinks.ElementAt(2).FindElements(By.TagName("a")); twitterURL = twitter.ElementAt(0).GetAttribute("href").ToString(); log.Info("Twitter URL:" + twitterURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify Twitter URL Assert.AreEqual("http://www.theiet.org/policy/media/follow/twitter.cfm?origin=foot-social", twitterURL); // Verify Twitter Request Status twitterStatus = uf.getStatusCode(new Uri(twitterURL.ToString())); Assert.AreEqual("OK", twitterStatus); // Verify Twitter icon title text Assert.AreEqual("Twitter icon", twitter.ElementAt(0).FindElement(By.TagName("img")).GetAttribute("title").ToString()); // Verify Linkedin icon is present and it's status linkedin = myCommunityLinks.ElementAt(3).FindElements(By.TagName("a")); linkedinURL = linkedin.ElementAt(0).GetAttribute("href").ToString(); log.Info("Linkedin URL:" + linkedinURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify Linkedin URL Assert.AreEqual("http://www.theiet.org/policy/media/follow/linkedin.cfm?origin=foot-social", linkedinURL); // Verify Linkedin Request Status linkedinStatus = uf.getStatusCode(new Uri(linkedinURL.ToString())); Assert.AreEqual("OK", linkedinStatus); // Verify Linkedin icon title text Assert.AreEqual("LinkedIn icon", linkedin.ElementAt(0).FindElement(By.TagName("img")).GetAttribute("title").ToString()); // Verify Youtube icon is present and it's status youTube = myCommunityLinks.ElementAt(4).FindElements(By.TagName("a")); youTubeURL = youTube.ElementAt(0).GetAttribute("href").ToString(); log.Info("YouTube URL:" + youTubeURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify YouTube URL Assert.AreEqual("http://www.theiet.org/policy/media/follow/youtube.cfm?origin=foot-social", youTubeURL); // Verify YouTube Request Status youTubeStatus = uf.getStatusCode(new Uri(youTubeURL.ToString())); Assert.AreEqual("OK", youTubeStatus); // Verify four sections are present in footer footerSection = driver.FindElements(By.CssSelector(or.readingXMLFile("BottomBar", "footerFourSections", "TVWebPortalOR.xml"))); cntFooterSections = footerSection.Count(); Assert.AreEqual(1, cntFooterSections); footerFourSections = footerSection.ElementAt(0).FindElements(By.TagName("div")); log.Info("Total Footer Sections:" + footerFourSections.Count + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(4, footerFourSections.Count); // {This needs to be taken from Test Data - Currently it is mentioned in test script} // Verify About the IET section myIETHeader = footerFourSections.ElementAt(0).FindElement(By.TagName("h4")).Text.ToString(); log.Info("My IET Header:" + myIETHeader + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify My IET section header text Assert.AreEqual("About the IET", myIETHeader); abtIET = footerFourSections.ElementAt(0).FindElement(By.TagName("ul")).FindElements(By.TagName("li")); // Verify expected no. of links are present under About the IET Assert.AreEqual(5, abtIET.Count()); // Verifying all links present under 'About the IET' section foreach (String val in arrAbtIET) { log.Info("Verifying " + val + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(abtIET.ElementAt(cntGlobal).FindElement(By.TagName("a")).Text, val); abtLinksURL = abtIET.ElementAt(cntGlobal).FindElement(By.TagName("a")).GetAttribute("href").ToString(); abtLinkStatus = uf.getStatusCode(new Uri(myCommunityURL.ToString())); Assert.AreEqual("OK", abtLinkStatus); cntGlobal++; } // Verify IET.tV help section IETTvHelp = footerFourSections.ElementAt(1).FindElement(By.TagName("h4")).Text.ToString(); log.Info("IET TV Help:" + IETTvHelp + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify IET TV. help section header text Assert.AreEqual("IET.tv help", IETTvHelp); cntGlobal = 0; abtHelp = footerFourSections.ElementAt(1).FindElement(By.TagName("ul")).FindElements(By.TagName("li")); // Verify expected no. of links are present under 'IET.tv help' Assert.AreEqual(7, abtHelp.Count()); // Verifying all links present under 'IET.tv help' section foreach (String val in arrIETHelp) { log.Info("Verifying " + val + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(abtHelp.ElementAt(cntGlobal).FindElement(By.TagName("a")).Text, val); String newVal = val.Replace(" ", "-"); if (cntGlobal == 0) { IEThelpURL = driver.Url.ToString() + "?" + newVal.ToLower(); } else if (cntGlobal == 1 || cntGlobal == 4) { IEThelpURL = driver.Url.ToString() + "?services=h" + newVal.ToLower(); } else { IEThelpURL = driver.Url.ToString() + "?services=" + newVal.ToLower(); } log.Info("IET HELP URL:= " + IEThelpURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); IEThelpStatus = uf.getStatusCode(new Uri(IEThelpURL.ToString())); Assert.AreEqual("OK", IEThelpStatus); cntGlobal++; } // Verify IET.tv account types section TvAccType = footerFourSections.ElementAt(2).FindElement(By.TagName("h4")).Text.ToString(); log.Info("IET TV Account Types:" + TvAccType + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify IET TV. account types header text Assert.AreEqual("IET.tv account types", TvAccType); cntGlobal = 0; abtAccType = footerFourSections.ElementAt(2).FindElement(By.TagName("ul")).FindElements(By.TagName("li")); // Verify expected no. of links are present under 'IET.tv account types' Assert.AreEqual(5, abtAccType.Count()); // Verifying all links present under 'IET.tv help' section foreach (String val in arrAccType) { log.Info("Verifying " + val + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(abtAccType.ElementAt(cntGlobal).FindElement(By.TagName("a")).Text, val); String newVal = val.Replace(" ", "-"); if (cntGlobal == 0 || cntGlobal == 3) { IETAccTypeURL = driver.Url.ToString() + "?services=a" + newVal.ToLower(); } else { IETAccTypeURL = driver.Url.ToString() + "?services=" + newVal.ToLower(); } log.Info("IET Acc Type URL:= " + IETAccTypeURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); IETAccTypeStatus = uf.getStatusCode(new Uri(IETAccTypeURL.ToString())); Assert.AreEqual("OK", IETAccTypeStatus); cntGlobal++; } // Verify Other IET websites section othIETSites = footerFourSections.ElementAt(3).FindElement(By.TagName("h4")).Text.ToString(); log.Info("Other IET WebSites:" + othIETSites + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify IET TV. help section header text Assert.AreEqual("Other IET websites", othIETSites); cntGlobal = 0; abtOthSites = footerFourSections.ElementAt(3).FindElement(By.TagName("ul")).FindElements(By.TagName("li")); Assert.AreEqual(9, abtOthSites.Count()); // Verifying all links present under 'About the IET' section foreach (String val in arrOthSites) { if (cntGlobal != 3) { log.Info("Verifying " + val + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(abtOthSites.ElementAt(cntGlobal).FindElement(By.TagName("a")).Text, val); othLinksURL = abtOthSites.ElementAt(cntGlobal).FindElement(By.TagName("a")).GetAttribute("href").ToString(); log.Info("Other IET Websites:= " + othLinksURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); othLinkStatus = uf.getStatusCode(new Uri(othLinksURL.ToString())); Assert.AreEqual("OK", othLinkStatus); } cntGlobal++; } // Verify Bottom Footer - Cookies, Privacy statement etc. cntGlobal = 0; bottomFooter = driver.FindElements(By.CssSelector(or.readingXMLFile("BottomBar", "bottomFooter", "TVWebPortalOR.xml"))); // Verify Bottom Footer is present Assert.AreEqual(1, bottomFooter.Count()); bottomFooterList = bottomFooter.ElementAt(0).FindElement(By.TagName("div")).FindElements(By.TagName("a")); foreach (String val in arrBottomFooter) { log.Info("Verifying " + val + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); // Verify bottom footer value is present as expected Assert.AreEqual(val, bottomFooterList.ElementAt(cntGlobal).Text); bottomFooterURL = bottomFooterList.ElementAt(cntGlobal).GetAttribute("href").ToString(); log.Info("Bottom Footer URL := " + bottomFooterURL + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); bottomLinkStatus = uf.getStatusCode(new Uri(bottomFooterURL.ToString())); Assert.AreEqual("OK", bottomLinkStatus); cntGlobal++; } // Verify Copyright text copyRightText = driver.FindElement(By.CssSelector(or.readingXMLFile("BottomBar", "copyRight", "TVWebPortalOR.xml"))).FindElement(By.TagName("p")).Text.ToString(); log.Info("Copyright text:=" + copyRightText + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual("© 2015 The Institution of Engineering and Technology is registered as a Charity in England & Wales (no 211014) and Scotland (no SC038698)", copyRightText); } catch (Exception e) { log.Error(e.Message + " at line:" + new StackTrace(true).GetFrame(0).GetFileLineNumber()); Assert.AreEqual(true, false); } }
public static void WaitForLoadingOverlays(IWebDriver driver, int timeout = 5) { List <IWebElement> loadingOLelements = driver.FindElements(By.ClassName("loadingoverlay")).ToList(); loadingOLelements.ForEach(e => WaitForHidingOfElement(e, driver, timeout)); }
private void metroButton2_Click(object sender, EventArgs e) { driver = new ChromeDriver(Directory.GetCurrentDirectory()); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); driver.Url = "https://tuicruises.com/kreuzfahrt-buchen"; driver.FindElement(By.CssSelector("input[type='submit'][value='Reise finden']")).Click(); wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("filter-options-toggle"))); driver.FindElement(By.Id("filter-options-toggle")).Click(); wait.Until(ExpectedConditions.ElementToBeClickable(By.CssSelector("div.noUiSlider.noUi-target.noUi-ltr.noUi-horizontal.noUi-background > div > div:nth-child(2)"))); /* * Actions action = new Actions(driver); * action.ClickAndHold(driver.FindElement(By.CssSelector("div.noUiSlider.noUi-target.noUi-ltr.noUi-horizontal.noUi-background > div > div:nth-child(2)"))); * action.Perform(); * * for (int i = 0; i < 120; i++) * { * action.MoveByOffset(-5, 0); * action.Perform(); * Console.WriteLine("Offset: {0} Tage: {1}", i, driver.FindElement(By.CssSelector("[class='max']")).Text); * Thread.Sleep(100); * } * * //action.ClickAndHold(driver.FindElement(By.CssSelector("div.noUiSlider.noUi-target.noUi-ltr.noUi-horizontal.noUi-background > div > div:nth-child(2)"))).MoveByOffset(-100, 0).Release(); * //action.Perform(); */ try { selectMaxDays(driver, Int32.Parse(txtCruiseDays.Text)); } catch (Exception exception) { selectMaxDays(driver, 42); } wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("searchoptionblocker"))); driver.FindElement(By.Id("startingPort-6")).Click(); wait.Until(ExpectedConditions.InvisibilityOfElementLocated(By.Id("searchoptionblocker"))); IList <IWebElement> reisen = driver.FindElements(By.CssSelector("div[class='route-item']")); Console.WriteLine("Anzahl der Reisen: {0}", reisen.Count); IList <IWebElement> clearedlist = getRealReisen(reisen); Console.WriteLine("Cleared: {0}", clearedlist.Count); IList <CruiseData> rawData = getCruiseData(clearedlist); gridFoundCruises.DataSource = rawData; IList <CruiseData> compareList = ExcelLoader.getCruisedataFromExcel(); Console.WriteLine("SIZE COMPARELIST: {0}", compareList.Count); var enumList = compareList.Except(rawData).ToList(); var enumList2 = rawData.Except(compareList).ToList(); Console.WriteLine("ENUMLIST COUNT: " + enumList.Count); Console.WriteLine("ENUMLIST2 COUNT: " + enumList2.Count); //var diffList = getDiffList(compareList, rawData); if (compareList.Equals(ExcelLoader.getCruisedataFromExcel())) { Console.WriteLine("GLEICH"); } else { Console.WriteLine("NEIN"); } // driver.Quit(); }
public IWebElement Region(string region) => _driver.FindElements(By.CssSelector("li.riotbar-region-option")).FirstOrDefault(r => r.Text == region);
public int CheckboxCount() { return(_driver.FindElements(By.XPath("//input[@type='checkbox']")).Count()); }