public SeleniumSteps WaitUntilZero() { var wait = new WebDriverWait(_driver, new TimeSpan(1, 0, 0)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("buyingtools-add-to-cart-button"))); return this; }
// This should be replaced for any given application; this isn't a one-size-fits-all sort of thing. public static IWebElement GetElementFromActivePage(this IWebDriver driver, string cssSelector, double timeoutSeconds = 20) { IWebElement element = null; var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutSeconds)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(WebDriverTimeoutException),typeof(UnhandledAlertException)); try { element = wait.Until(drv => { try { return drv.FindElement(By.CssSelector(cssPrefix + cssSelector)); } catch (NoSuchElementException ex) { return null; } }); } catch (WebDriverTimeoutException ex) { return null; } return element; }
/// <summary> /// Checks that the search results contain the specified string on a SearchDialog. /// Throws an exception on failure. /// /// </summary> /// <param name="expected">The string to check for.</param> public static void CheckConstituentSearchResultsContain(string expected) { var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); ICollection<IWebElement> nameFieldElements = new Collection<IWebElement>(); waiter.Until(d => { var constituentSearchResultsToolbarElement = Driver.FindElement(By.XPath(getXResultsBar)); nameFieldElements = Driver.FindElements(By.XPath(getXGridNameField)); var constituentSearchResultsGrid = Driver.FindElement(By.XPath(getXSearchResultsGrid)); if ((nameFieldElements == null || !constituentSearchResultsGrid.Displayed || !constituentSearchResultsToolbarElement.Text.Contains("found"))) return false; var names = from element in nameFieldElements select element.Text; if (!names.Contains(expected)) return false; //{ // throw new Exception(String.Format("CheckConstituentResultsContain Failed: Expected Name '{0}' was not found in the Results.", expected)); //} return true; }); }
public static WebDriverWait GetWebDriverWait(int timeOutInSeconds) { var wait = new WebDriverWait(ObjectRepository.Driver, TimeSpan.FromSeconds(timeOutInSeconds)); wait.PollingInterval = TimeSpan.FromMilliseconds(250); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); return wait; }
public static void WaitUntilAvailable(Func<IWebDriver, object> condition) { IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(30)); wait.Timeout = TimeSpan.FromSeconds(60); wait.PollingInterval = TimeSpan.FromSeconds(1); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.Until(condition); }
public void SelectIssueType(string issueType) { var issueField = BaseElement.FindElement(By.Id("issuetype-field")); issueField.SendKeys(issueType+Keys.Enter); var wait = new WebDriverWait(_Af.Driver, TimeSpan.FromSeconds(AutomationFramework.Timeout)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); wait.Until(_ => BaseElement.FindElement(By.XPath(WidgetLoadXPath)) .GetAttribute("class") != LoadingClass); }
public static WebDriverWait GetWebdriverWait(TimeSpan timeout) { ObjectRepository.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1)); WebDriverWait wait = new WebDriverWait(ObjectRepository.Driver, timeout) { PollingInterval = TimeSpan.FromMilliseconds(500), }; wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); return wait; }
public static IWebElement FindElement(this IWebDriver driver, By by, int timeoutInSeconds) { if (timeoutInSeconds > 0) { var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutInSeconds)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); return wait.Until(drv => drv.FindElement(by)); } return driver.FindElement(by); }
public static IWebElement UntilVisible(By by, IWebDriver driver, TimeSpan timeOut) { WebDriverWait wdWait = new WebDriverWait(driver, timeOut); wdWait.IgnoreExceptionTypes ( typeof(ElementNotVisibleException), typeof(NoSuchElementException), typeof(StaleElementReferenceException) ); return wdWait.Until(ExpectedConditions.ElementIsVisible(by)); }
public void TestExpCondition() { NavigationHelper.NavigateToUrl("https://www.udemy.com/"); ObjectRepository.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1)); WebDriverWait wait = new WebDriverWait(ObjectRepository.Driver, TimeSpan.FromSeconds(50)); wait.PollingInterval = TimeSpan.FromMilliseconds(250); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); wait.Until(ExpectedConditions.ElementExists(By.XPath("//input[@type='search']"))).SendKeys("HTML"); ButtonHelper.ClickButton(By.CssSelector(".home-search-btn")); wait.Until(ExpectedConditions.ElementExists(By.XPath("//*[@id='courses']/li[12]/a/div[2]/div[1]/div/span"))).Click(); Console.WriteLine("Title : {0}", wait.Until(ExpectedConditions.TitleContains("u"))); wait.Until(ExpectedConditions.ElementExists(By.XPath("//a[contains(text(),'Login')]"))).Click(); wait.Until(ExpectedConditions.ElementExists(By.XPath("//div[@class='loginbox-v4 js-signin-box']"))); }
public static IWebElement WaitFor(By by, TimeSpan timeout) { var timeouts = Driver.Manage().Timeouts(); timeouts.ImplicitlyWait(TimeSpan.MinValue); try { IWait<IWebDriver> wait = new WebDriverWait(Driver, timeout); wait.IgnoreExceptionTypes(DefaultWaitForElementIgnoredExceptions); return wait.Until(drv => drv.FindElement(by)); } finally { timeouts.ImplicitlyWait(DefaultImplicitlyWait); } }
public static bool WaitForElement(IWebDriver driver, TimeSpan timeout, By elementSelector) { try { var wait = new WebDriverWait(driver, timeout); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.Until(x => x.FindElement(elementSelector)); } catch { return false; } return true; }
public static void WaitForAjaxElementVisible(this IWebDriver driver, By byElement, double timeoutSeconds) { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeoutSeconds)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); wait.Until(x => { IWebElement element = x.FindElement(byElement); if (element != null) { return element.Displayed == true; } return false; }); }
public void TestDynamciWait() { NavigationHelper.NavigateToUrl("https://www.udemy.com/"); ObjectRepository.Driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(1)); WebDriverWait wait = new WebDriverWait(ObjectRepository.Driver, TimeSpan.FromSeconds(50)); wait.PollingInterval = TimeSpan.FromMilliseconds(250); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); // Console.WriteLine(wait.Until(waitforTitle())); // IWebElement element = wait.Until(waitforElement()); // element.SendKeys("java"); wait.Until(this.WaitforElement()).SendKeys("health"); ButtonHelper.ClickButton(By.CssSelector(".home-search-btn")); wait.Until(this.WaitforLastElemet()).Click(); Console.WriteLine("Title : {0}", wait.Until(this.WaitforpageTitle())); }
public static WebDriverWait GetWebDriverWait(int timeOutInSeconds) { if (_wait != null) { Logger.Info(" Wait Object Created "); return _wait; } _wait = new WebDriverWait(ObjectRepository.Driver, TimeSpan.FromSeconds(timeOutInSeconds)) { PollingInterval = TimeSpan.FromMilliseconds(250), }; _wait.IgnoreExceptionTypes(typeof(NoSuchElementException),typeof(ElementNotVisibleException)); Logger.Info(" Wait Object Created "); return _wait; }
public static void DeleteQuery(string xQuery,string xDeleteQuery) { WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); wait.IgnoreExceptionTypes(typeof(InvalidOperationException)); Actions clicker = new Actions(Driver); try { wait.Until(d => { QueryLinkElement = d.FindElement(By.XPath(xQuery)); if (QueryLinkElement == null || QueryLinkElement.Displayed == false || QueryLinkElement.Enabled == false) return false; return true; }); } catch (Exception) { throw new NoSuchElementException(); } wait.Until(d => { clicker.ContextClick(QueryLinkElement).Perform(); DeleteQueryLinkElement = d.FindElement(By.XPath(xDeleteQuery)); if (DeleteQueryLinkElement == null || DeleteQueryLinkElement.Displayed == false || DeleteQueryLinkElement.Enabled == false) return false; DeleteQueryLinkElement.Click(); return true; }); wait.Until(d => { YesReallyDeleteElement = d.FindElement(By.XPath(getXButton("Yes"))); if (YesReallyDeleteElement == null || YesReallyDeleteElement.Displayed == false) return false; YesReallyDeleteElement.Click(); return true; }); }
public static void WaitForElement(By SearchBy, int TimeoutSeconds, bool IsIgnoreElementVisibilty) { try { Browser.SwitchToMostRecentBrowser(); WebDriverWait wait = new WebDriverWait(TestObject.Driver, TimeSpan.FromSeconds(TimeoutSeconds)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); if (IsIgnoreElementVisibilty) wait.Until(ExpectedConditions.ElementExists(SearchBy)); else wait.Until(ExpectedConditions.ElementIsVisible(SearchBy)); } catch (Exception) { // ignored } }
public static bool ClickAndWaitForElement(this IWebElement webElement, IWebDriver driver, TimeSpan timeout, By elementSelector) { if (!ClickSafe(webElement)) return false; try { var wait = new WebDriverWait(driver, timeout); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.Until(x => x.FindElement(elementSelector)); } catch { return false; } return true; }
public Scraper(String ProxyType = null, String ProxyAddress = null, String ProxyUsername = null, String ProxyPassword = null) { this.ProxyType = ProxyType; this.ProxyAddress = ProxyAddress; this.ProxyUsername = ProxyUsername; this.ProxyPassword = ProxyPassword; ChromeOptions options = new ChromeOptions(); var chromeDriverService = ChromeDriverService.CreateDefaultService(); chromeDriverService.HideCommandPromptWindow = true; //String username = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //if (username == @"DESKTOP-2KTBPSE\Valloon") //{ // var proxy = new Proxy(); // proxy.Kind = ProxyKind.Manual; // proxy.IsAutoDetect = false; // proxy.HttpProxy = proxy.SslProxy = "81.177.48.86:80"; // options.Proxy = proxy; //} //options.AddArgument("--start-maximized"); //options.AddArgument("--auth-server-whitelist"); //options.AddArguments("--disable-extensions"); options.AddArgument("--ignore-certificate-errors"); options.AddArgument("--ignore-ssl-errors"); options.AddArgument("--system-developer-mode"); options.AddArgument("--no-first-run"); options.SetLoggingPreference(LogType.Driver, LogLevel.All); options.AddAdditionalCapability("useAutomationExtension", false); //chromeOptions.AddArguments("--disk-cache-size=0"); //options.AddArgument("--user-data-dir=" + m_chr_user_data_dir); #if !DEBUG options.AddArguments("--headless"); options.AddArguments("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36"); options.AddArguments("--disable-plugins-discovery"); //options.AddArguments("--profile-directory=Default"); //options.AddArguments("--no-sandbox"); //options.AddArguments("--incognito"); //options.AddArguments("--disable-gpu"); //options.AddArguments("--no-first-run"); //options.AddArguments("--ignore-certificate-errors"); //options.AddArguments("--start-maximized"); //options.AddArguments("disable-infobars"); //options.AddAdditionalCapability("acceptInsecureCerts", true, true); #endif if (ProxyType != null) { String m_chr_extension_dir = Environment.CurrentDirectory + "\\ChromeExtension"; options.AddArgument("--load-extension=" + m_chr_extension_dir + "\\Proxy-SwitchyOmega_v2.5.20"); //options.AddExtension(m_chr_extension_dir + "\\Proxy-SwitchyOmega_v2.5.20.crx"); } ChromeDriver = new ChromeDriver(chromeDriverService, options, TimeSpan.FromSeconds(DEFAULT_TIMEOUT_PAGELOAD)); ChromeDriver.Manage().Window.Position = new Point(0, 0); ChromeDriver.Manage().Window.Size = new Size(1200, 900); ChromeDriver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(5); JSE = (IJavaScriptExecutor)ChromeDriver; Wait = new WebDriverWait(ChromeDriver, TimeSpan.FromSeconds(180)); Wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); if (ProxyType != null) { ChromeDriver.Navigate().GoToUrl("chrome-extension://padekgcemlokbadohgkifijomclgjgif/options.html#!/profile/proxy"); String ip = ProxyAddress.Split(':')[0]; String port = ProxyAddress.Split(':')[1]; var selectProtocol = Wait.Until(drv => drv.FindElement(By.CssSelector("table.fixed-servers>tbody>tr>td:nth-of-type(2)>select"))); new SelectElement(selectProtocol).SelectByText(ProxyType); var inputServer = ChromeDriver.FindElement(By.CssSelector("table.fixed-servers>tbody>tr>td:nth-of-type(3)>input")); inputServer.Clear(); inputServer.SendKeys(ip); var inputPort = ChromeDriver.FindElement(By.CssSelector("table.fixed-servers>tbody>tr>td:nth-of-type(4)>input")); inputPort.Clear(); inputPort.SendKeys(port); JSE.ExecuteScript($"document.querySelector(\"a[ng-click=\'applyOptions()\']\").click();"); try { ChromeDriver.SwitchTo().Alert().Accept(); } catch { } } }
protected static void ignoreNoSuchElementException() { WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); }
public BasePage() { Wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException), typeof(StaleElementReferenceException)); }
/// <summary> /// Set the value of a field by copy pasting the value into the field and sending a Tab keystroke. /// </summary> /// <param name="xPath">The xPath to find an element for setting the value to.</param> /// <param name="value">The desired value of the element.</param> public static void SetTextField(string xPath, string value) { if (value == null) { return; } var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); //removed element from being a public field and moved to scope of method waiter.Until(d => { CopyToClipBoard(value); var fieldElement = d.FindElement(By.XPath(xPath)); if (fieldElement == null || !fieldElement.Displayed || !fieldElement.Enabled) { return(false); } fieldElement.Click(); var innerwaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); innerwaiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); try { innerwaiter.Until(dd => { if (!fieldElement.GetAttribute("class").Contains("focus")) { return(false); } return(true); }); } catch (WebDriverTimeoutException) { return(false); } fieldElement.SendKeys(Keys.Control + "a"); fieldElement.SendKeys(Keys.Control + "v"); try { innerwaiter.Until(dd => { //Sending a [Tab] triggers a submit on the field. This is needed for a dropdown and speeds up a required text field being set. fieldElement.SendKeys(Keys.Tab); if (fieldElement.GetAttribute("value") != value) { return(false); } return(true); }); } catch (WebDriverTimeoutException) { return(false); } catch (Exception Ex) { throw Ex; } return(true); }); }
// TODO refactor these two following functions and distill out common code and Xpaths // TODO move into CORE /// <summary> /// Delete the named part from the Content Gallery. /// </summary> /// <param name="name"></param> public static void DeletePart(string name) { SearchPartsByName(name); IList <IWebElement> partGridNameFieldElements = null; IWebElement partSearchResultsLineElement; var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(20)); wait.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); wait.Until(d => { partSearchResultsLineElement = Driver.FindElement(By.XPath(getXPartsSearchResultsLine)); partGridNameFieldElements = Driver.FindElements(By.XPath("//table[contains(@class,'DataGrid')]//span[./text()='" + name + "']")); if (partGridNameFieldElements == null || partSearchResultsLineElement.Displayed == false || partSearchResultsLineElement.Text.Contains("No")) { return(false); } foreach (var element in partGridNameFieldElements) { element.Click(); WaitClick(getXDeleteButton); IAlert alert = Driver.SwitchTo().Alert(); alert.Accept(); } return(true); }); // Need to check enabled first for this one !! GetEnabledElement("//div[contains(@class,'ExplorerTabs')]//td[./text()='Folders']"); WaitClick("//div[contains(@class,'ExplorerTabs')]//td[./text()='Folders']"); WaitClick("//span[./text()='Deleted Parts']"); GetDisplayedElement("//div[contains(@class,'ExplorerPath')]//span[./text()='Deleted Parts']"); wait.Until(d => { partSearchResultsLineElement = Driver.FindElement(By.XPath(getXPartsSearchResultsLine)); partGridNameFieldElements = Driver.FindElements(By.XPath("//table[contains(@class,'DataGrid')]//span[./text()='" + name + "']")); if (partGridNameFieldElements == null || partSearchResultsLineElement.Displayed == false || partSearchResultsLineElement.Text.Contains("No")) { return(false); } foreach (var element in partGridNameFieldElements) { element.Click(); WaitClick(getXDeleteButton); IAlert alert = Driver.SwitchTo().Alert(); alert.Accept(); } return(true); }); }
public ActionHelper(IWebDriver passedInWebdriver) { theWebdriver = passedInWebdriver; wait = new WebDriverWait(passedInWebdriver, TimeSpan.FromSeconds(waitTime)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException), typeof(InvalidOperationException), typeof(NoSuchElementException)); }
/// <summary> /// Set a Grid cell's value for a dropdown field. /// </summary> /// <param name="xPath">The xPath of the grid cell TD element.</param> /// <param name="value">The value to set the cell to.</param> public static void SetGridDropDown(string xPath, string value = "") { var setWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); setWaiter.Until(d => { try { var clickedWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)); clickedWaiter.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); clickedWaiter.Until(d1 => { try { //original field should be covered by the edit cell and therefore unclickable d1.FindElement(By.XPath(xPath)).Click(); return false; } catch (InvalidOperationException) { return true; } }); } catch (WebDriverTimeoutException) { return false; } var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); //click the dropdown arrow try { waiter.Until(d1 => { var dropdownArrow = d1.FindElement(By.XPath(getXGridEditCellDropdownArrow)); if (dropdownArrow == null || !dropdownArrow.Displayed || !dropdownArrow.Enabled) return false; dropdownArrow.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } //wait for the list to appear try { waiter.Until(d2 => { var dropdownList = d2.FindElement(By.XPath(getXDropdownListItems)); return dropdownList != null && dropdownList.Displayed; }); } catch (WebDriverTimeoutException) { return false; } //select the item in the list try { waiter.Until(d3 => { var dropdownItem = d3.FindElement(By.XPath(getXDropdownItem(value))); if (dropdownItem == null || !dropdownItem.Displayed || !dropdownItem.Enabled) return false; dropdownItem.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } //wait for the editgrid to be set try { ElementValueIsSet(getXGridEditCell, value); } catch (WebDriverTimeoutException) { return false; } //send enter on the edit grid try { waiter.Until(d4 => { var editField = d4.FindElement(By.XPath(getXGridEditCell)); if (editField == null || !editField.Displayed) return false; editField.SendKeys(Keys.Return); return true; }); } catch (WebDriverTimeoutException) { return false; } //ensure the original grid value has been set before continuing try { ElementValueIsSet(xPath, value); } catch (WebDriverTimeoutException) { return false; } return true; }); }
public void LoginToGmail() { Pages.loginPage.LogInToGmail(userEmail, userPassword, Utils.baseUrl); wait = new WebDriverWait(PropertiesCollection.driver, TimeSpan.FromSeconds(10)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); }
public static void WaitLoadElement(String XPath) { mWait.IgnoreExceptionTypes(typeof(NoSuchElementException)); mWait.Until(ExpectedConditions.ElementIsVisible(By.XPath(XPath))); }
/// <summary> /// Wait for a dialog to appear that has a unique is in the provided list of /// ids and return the matching id. /// </summary> /// <param name="supportedIds">A list of ids to wait for.</param> /// <returns>The first found matching id for a dialog that is visible with that id. /// If no id is found, a WebDriverTimeoutException is eventually thrown.</returns> public static string GetDialogId(IEnumerable<string> supportedIds) { var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); string returnDialogId = String.Empty; waiter.Until(d => { foreach (var dialogId in supportedIds) { try { var dialog = d.FindElement(By.XPath(getXDialogById(dialogId))); if (dialog == null || !dialog.Displayed) continue; returnDialogId = dialogId; return true; } catch (NoSuchElementException) { } } return false; }); if (returnDialogId == String.Empty) throw new WebDriverTimeoutException("No supported dialogId found."); return returnDialogId; }
public void IgnoreExceptionTypes(params Type[] exceptionTypes) { _wait.IgnoreExceptionTypes(exceptionTypes); }
/// <summary> /// None /// </summary> /// <param name="args">ユーザーID</param> static void Main(string[] args) { var chromeOptions = new ChromeOptions { PageLoadStrategy = PageLoadStrategy.Normal }; var urlList = new List <string>(); using IWebDriver driver = new ChromeDriver(chromeOptions); try { driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(3); driver.Navigate().GoToUrl("https://qiita.com/" + args[0] + "/lgtms"); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); var firstResult = wait.Until(e => e.FindElement(By.ClassName("st-Pager_count")).FindElement(By.TagName("span"))); var maxPage = int.Parse(firstResult.Text.Split("/")[1].Trim()); for (int i = 0; i < maxPage; i++) { if (i != 0) { driver.Url = "https://qiita.com/" + args[0] + "/lgtms?page=" + (i + 1); } var fwait = new WebDriverWait(driver, TimeSpan.FromSeconds(30)) { PollingInterval = TimeSpan.FromSeconds(5), }; fwait.IgnoreExceptionTypes(typeof(NoSuchElementException)); var result = fwait.Until(e => e.FindElement(By.CssSelector(".ItemListArticleWithAvatar__Item-sc-1jj9c6g-0.dzFkMp"))); var urlEls = driver.FindElements(By.CssSelector(".ItemListArticleWithAvatar__Item-sc-1jj9c6g-0.dzFkMp")).Select(x => x.FindElements(By.TagName("a"))[x.FindElements(By.TagName("a")).Count - 2]); var urls = urlEls.Select(x => x.GetAttribute("href")); urlList.AddRange(urls); } } catch (Exception ex) { driver.Quit(); driver.Dispose(); return; } finally { driver.Quit(); driver.Dispose(); } var directory = Path.Combine(Directory.GetParent(Assembly.GetExecutingAssembly().Location).FullName, "OUTPUT"); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } if (File.Exists(Path.Combine(directory, "output.txt"))) { File.Move(Path.Combine(directory, "output.txt"), Path.Combine(directory, "output_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".txt")); } StreamWriter sw = new StreamWriter(Path.Combine(directory, "output.txt"), false, Encoding.UTF8); foreach (var item in urlList) { sw.Write(item + sw.NewLine); } sw.Close(); sw.Dispose(); }
public void PageHasLoaded() { _wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); _wait.PollingInterval = TimeSpan.FromSeconds(2); _wait.Until(driver => PageFooter); }
/// <summary> /// Check if additional pages exist for a datalist to load. If so load the page. /// </summary> /// <returns>Returns true if an additional page was found and clicked, false otherwise.</returns> public static bool AdditionalDatalistPagesExist(string sectionCaption) { WebDriverWait waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(1)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException), typeof(ElementClickInterceptedException)); bool additionalPage = false; //get current datalist page number int datalistPage = Int32.MaxValue; try { waiter.Until(d => { IWebElement currentDatalistPage = d.FindElement(By.XPath(getXSectionDatalistCurrentPageIndex(sectionCaption))); if (currentDatalistPage != null && currentDatalistPage.Displayed) { datalistPage = Int32.Parse(currentDatalistPage.Text); return(true); } return(false); }); } catch (WebDriverTimeoutException) { return(false); } //see if button exists with higher page index and click it waiter.Until(d => { ICollection <IWebElement> datalistPageButtons = d.FindElements(By.XPath(getXSectionDatalistPageIndexButtons(sectionCaption))); foreach (IWebElement button in datalistPageButtons) { try { int nextPageIndex = Int32.Parse(button.Text); if (button.Displayed && button.Enabled && nextPageIndex == datalistPage + 1) { additionalPage = true; button.Click(); //wait until the current page index is the next page WebDriverWait innerWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); innerWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException), typeof(ElementClickInterceptedException)); innerWaiter.Until(dd => { IWebElement currentIndex = d.FindElement(By.XPath(getXSectionDatalistCurrentPageIndex(sectionCaption))); if (currentIndex != null && currentIndex.Displayed && Int32.Parse(currentIndex.Text) == nextPageIndex) { return(true); } return(false); }); return(true); } } catch (FormatException) { } } return(false); }); return(additionalPage); }
public SignUpPage(IWebDriver driver) { _driver = driver; _driverWait = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)); _driverWait.IgnoreExceptionTypes(typeof(NoSuchElementException)); }
/// <summary> /// Set an IFrame HTML field's value. /// </summary> /// <param name="xPath">The xPath of the IFrame. Advised to use Dialog.getXIFrame()</param> /// <param name="value">The value to set in the HTML body of the IFrame.</param> public static void SetHtmlField(string xPath, string value = "") { if (value == null) return; CopyToClipBoard(value); var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); waiter.Until(d => { var iframeElement = d.FindElement(By.XPath(xPath)); if (iframeElement == null || !iframeElement.Displayed || !iframeElement.Enabled) return false; iframeElement.Click(); iframeElement.SendKeys(Keys.Control + "a"); iframeElement.SendKeys(Keys.Control + "v"); iframeElement.SendKeys(Keys.Tab); return true; }); /* * The iframe HTML fields do not have any children. the next child is a '#document' * element that cannot be queried or discovered by xPath. * * The IFrame's value attribute will not be set to the desired value. The <p> child DOM element * of the IFrame has its text set to the desired value, but a different selector from xPaths needs * to be used in order to access it. * * To get that element via xPaths you can only start your root search with the top level HTML * element in the dialog. ie '//html/body[contains(@class, 'mceContentBody')]' * */ //waiter.Until(d => //{ // //the HTML iframes have the value set to be checked for as a nested <p> element // IWebElement htmlBodyElement = d.FindElement(By.XPath(getXIFrameHtmlBodyP)); // if (htmlBodyElement == null // || !htmlBodyElement.Displayed || !htmlBodyElement.Enabled || htmlBodyElement.Text != value) return false; // return true; //}); }
/// <summary> /// Set a field's value using the associated search dialog to the first found item in the search results. /// </summary> /// <param name="xPath">The xPath of the field to set.</param> /// <param name="searchFieldxPath">The xPath of the search dialog's field to set.</param> /// <param name="value">The value to set and use as search criteria in the specified search dialog field.</param> public static void SetSearchList(string xPath, string searchFieldxPath, string value = "") { /* * A formfield with a searchlist does different actions based on the input value. * If an existing item is input and enter is hit, then the searchlist appears. If * a partial item name is input and enter is hit, then an auto-search in the background * is done to try and find a suggested item. If an item is found then auto-complete changes * the current value to the suggest value. If no suggested item is found, a searchlist appears. * * This makes is difficult to come up with consistent behavior setting the value directly into the field * and checking for UI element changes. Instead I am defaulting to opening the searchlist always, * looking for the provided value, and selecting the first found element. */ var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); waiter.Until(d => { IWebElement searchField = GetEnabledElement(xPath); if (searchField == null || searchField.Displayed == false || searchField.Enabled == false) return false; return true; }); GetEnabledElement(xPath); //click the search button WaitClick(getXInputSearchTrigger(xPath)); //enter the search criteria SetTextField(searchFieldxPath, value); //search WaitClick(SearchDialog.getXSearchButton); //select WaitClick(SearchDialog.getXSelectButton); ElementValueIsNotNullOrEmpty(xPath); }
public TextBoxPage(IWebDriver driver) { _driver = driver; _driverWait = new WebDriverWait(_driver, TimeSpan.FromSeconds(3)); _driverWait.IgnoreExceptionTypes(); }
public static void NewLayout(string Layoutname, String Description) { WaitClick(getXNewLayoutButton); WebDriverWait wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); wait.IgnoreExceptionTypes(typeof(InvalidOperationException)); //wait.Until(d => //{ // if (NewLayoutButtonElement == null) return false; // NewLayoutButtonElement.Click(); // return true; //}); // Do the popup thing like it's 1995 .... // This assumes the newly opened window will be the last handle on the list and that the parent is first on the list. // Its worked fine so far so its KISS for me but if it starts mis-identifying windows we could select by Driver.Title Driver.SwitchTo().Window(Driver.WindowHandles[Driver.WindowHandles.Count - 1]); // SetTextfield seems to have problems in BBIS :) //SetTextField(getXNewLayoutLayoutName, Layoutname); //SetTextField(getXNewLayoutLayoutDescription, Description); IWebElement NewLayoutLayoutNameElement = Driver.FindElement(By.XPath(getXNewLayoutLayoutName)); IWebElement NewLayoutLayoutDescriptionElement = Driver.FindElement(By.XPath(getXNewLayoutLayoutDescription)); wait.Until(d => { if (NewLayoutLayoutNameElement == null || NewLayoutLayoutDescriptionElement == null) { return(false); } NewLayoutLayoutNameElement.Clear(); NewLayoutLayoutDescriptionElement.Clear(); return(true); }); //try //{ NewLayoutLayoutNameElement.SendKeys(Layoutname); NewLayoutLayoutDescriptionElement.SendKeys(Description); //} catch (RuntimeBinderException) { } WaitClick(getXNewLayoutNextButton); //wait.Until(d => //{ // if (NewLayoutNextButton == null) return false; // NewLayoutNextButton.Click(); // return true; //}); WaitClick(getXNewLayoutSaveButton); //wait.Until(d => //{ // if (NewLayoutSaveButton == null) return false; // NewLayoutSaveButton.Click(); // return true; //}); Driver.SwitchTo().Window(Driver.WindowHandles[0]); // This section is here to make sure we don't move on before the driver has refereshed itself // after the window switch - wait until we stop getting 'Stale Handles' for the search field // back on the main Layout page. wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); wait.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); wait.Until(d => { IWebElement FilterByNameFieldElement = d.FindElement(By.XPath(getXFilterByNameField)); if (FilterByNameFieldElement == null) { return(false); } FilterByNameFieldElement.Clear(); return(true); }); }
/// <summary> /// Open a Functional Area by caption. /// </summary> /// <param name="caption">The caption(name) of the Functional Area to open.</param> public static void OpenFunctionalArea(string caption) { //ensure the basic components of the current panel have loaded. Clicking too soon can lead to no navigation. GetDisplayedElement(Panel.getXPanelHeader()); /* * The element to click can reside in the top menu bar, or be hidden in the additional * functional areas expander. */ if (ExistsNow(getXExtTab(caption))) WaitClick(getXExtTab(caption)); else { WebDriverWait navigateWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); navigateWaiter.IgnoreExceptionTypes(typeof (InvalidOperationException)); //retry logic navigateWaiter.Until(d1 => { WebDriverWait clickWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); clickWaiter.IgnoreExceptionTypes(typeof (InvalidOperationException)); try { clickWaiter.Until(d2 => { IWebElement additionalMenuItems = d2.FindElement(By.XPath(getXMenuMore)); if (!additionalMenuItems.Displayed) return false; additionalMenuItems.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } try { clickWaiter.Until(d2 => { IWebElement additionalMenuItems = d2.FindElement(By.XPath(getXExtMenuTab(caption))); if (!additionalMenuItems.Displayed) return false; additionalMenuItems.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } return true; }); } }
/// <summary> /// Open a Functional Area by caption. /// </summary> /// <param name="caption">The caption(name) of the Functional Area to open.</param> public static void OpenFunctionalArea(string caption) { //ensure the basic components of the current panel have loaded. Clicking too soon can lead to no navigation. GetDisplayedElement(Panel.getXPanelHeader()); /* * The element to click can reside in the top menu bar, or be hidden in the additional * functional areas expander. */ if (ExistsNow(getXExtTab(caption))) { WaitClick(getXExtTab(caption)); } else { WebDriverWait navigateWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); navigateWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); //retry logic navigateWaiter.Until(d1 => { WebDriverWait clickWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); clickWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); try { clickWaiter.Until(d2 => { IWebElement additionalMenuItems = d2.FindElement(By.XPath(getXMenuMore)); if (!additionalMenuItems.Displayed) { return(false); } additionalMenuItems.Click(); return(true); }); } catch (WebDriverTimeoutException) { return(false); } try { clickWaiter.Until(d2 => { IWebElement additionalMenuItems = d2.FindElement(By.XPath(getXExtMenuTab(caption))); if (!additionalMenuItems.Displayed) { return(false); } additionalMenuItems.Click(); return(true); }); } catch (WebDriverTimeoutException) { return(false); } return(true); }); } }
/// <summary> /// Click on the functional area link that navigates to a panel. /// </summary> /// <param name="groupCaption">The group header caption of the task.</param> /// <param name="linkCaption">The caption of the task link.</param> /// <param name="headerText">The header caption of the desired panel to navigate to.</param> public static void OpenLinkToPanel(string groupCaption, string linkCaption, string headerText) { var navigateWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); navigateWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); navigateWaiter.Until(d => { var panelHeader = d.FindElement(By.XPath(Panel.getXPanelHeader())); if (panelHeader.Text != headerText) { WaitClick(getXFunctionalAreaTask(groupCaption, linkCaption)); return false; } return true; }); }
static void Main(string[] args) { Console.WriteLine("How many votes?"); uint votes = 0; while (votes <= 0) { string line = Console.ReadLine(); if (!uint.TryParse(line, out votes) || votes <= 0) { Console.WriteLine("Invalid input. Input must also be bigger than 0"); } } uint totalDone = 0; try { for (; totalDone < votes; totalDone++) { using (ChromeDriver driver = new ChromeDriver()) { driver.Navigate().GoToUrl(@"https://temp-mail.org/"); IWebElement mailElement = driver.FindElement(By.XPath("//input[@data-original-title='Your temporary Email address']")); string mailAddress = mailElement.GetAttribute("value"); string mailWindowHandle = driver.WindowHandles.Last(); GoToUrlInNewTab(driver, "NameTab", @"http://www.fakenamegenerator.com/gen-random-nl-nl.php"); IWebElement addressElement = driver.FindElement(By.ClassName("address")); IWebElement nameElement = addressElement.FindElement(By.TagName("h3")); string name = nameElement.Text; IWebElement fullAddressElement = addressElement.FindElement(By.ClassName("adr")); string state = fullAddressElement.Text.Split(new string[] { " " }, StringSplitOptions.None)[1]; GoToUrlInNewTab(driver, "VoteTab", @"http://www.stoffenbeurs.nl/naaimachine-winnen-janome/?ref_id=t8447719"); driver.SwitchTo().Frame("uvembed31169"); IWebElement nameInputElement = driver.FindElement(By.Name("txt_name")); nameInputElement.Clear(); nameInputElement.SendKeys(name); IWebElement emailInputElement = driver.FindElement(By.Name("txt_email")); emailInputElement.Clear(); emailInputElement.SendKeys(mailAddress); IWebElement stateInputElement = driver.FindElement(By.Name("woonplaats")); stateInputElement.Clear(); stateInputElement.SendKeys(state); IWebElement submitElement = driver.FindElement(By.Id("lead_button")); IJavaScriptExecutor executor = (IJavaScriptExecutor)driver; executor.ExecuteScript("arguments[0].click()", submitElement); driver.SwitchTo().Window(mailWindowHandle); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(600)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(ElementNotVisibleException)); IWebElement viewMailElement = wait.Until(x => x.FindElement(By.XPath("//span[@class='glyphicon glyphicon-chevron-right']"))).FindElement(By.XPath("..")); string hrefView = viewMailElement.GetAttribute("href"); driver.Navigate().GoToUrl(hrefView); IWebElement confirmationElement = driver.FindElement(By.XPath("//a[text() = 'Bevestig mijn deelname']")); string hrefConfirmation = confirmationElement.GetAttribute("href"); driver.Navigate().GoToUrl(hrefConfirmation); CloseWindows(driver); } } Console.WriteLine(String.Format("All {0} votes done!", votes)); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(String.Format("Something went wrong, was able to do {0} votes", totalDone)); } Console.ReadKey(); }
/// <summary> /// Set a Grid cell's value for a text field. /// </summary> /// <param name="xPath">The xPath of the grid cell TD element.</param> /// <param name="value">The value to set the cell to.</param> public static void SetGridTextField(string xPath, string value = "") { if (value == null) return; var setWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); setWaiter.Until(d => { //WaitClick(xPath); //WaitClick(getXGridEditCell); //WaitClick(getXGridFocusedEditCell); //Have to click several elements potentially. there are rare moments when the edit field is weirdly on the 2nd //row when trying to click the first row. try { var clickedWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)); clickedWaiter.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); clickedWaiter.Until(d1 => { try { //original field should be covered by the edit cell and therefore unclickable d1.FindElement(By.XPath(xPath)).Click(); return false; } catch (InvalidOperationException) { return true; } }); } catch (WebDriverTimeoutException) { return false; } CopyToClipBoard(value); try { var setValueWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)); setValueWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); setValueWaiter.Until(d2 => { var element = d2.FindElement(By.XPath(getXGridEditCell)); if (element == null || !element.Displayed || !element.Enabled) return false; element.SendKeys(Keys.Control + "a"); element.SendKeys(Keys.Control + "v"); return true; }); //wait for value of edit cell to be set setValueWaiter.Until(d3 => { var element = d3.FindElement(By.XPath(getXGridEditCell)); if (element != null && element.Displayed && element.Enabled && (element.Text == value || element.GetAttribute("value") == value)) { element.SendKeys(Keys.Return); return true; } return false; }); //ensure the original grid value has been set before continuing ElementValueIsSet(xPath, value); } catch (WebDriverTimeoutException) { return false; } return true; }); }
public List <Stock> Scrape() { ChromeOptions options = new ChromeOptions(); // Add capbilities to ChromeOptions options.AddArguments("test -Type", "--ignore-certificate-errors", "--disable-gpu", "disable-popups"); // Launching browser with desired capabilities + proper binary file location IWebDriver driver = new ChromeDriver(@"\Users\gregs\Desktop\CD\CapstoneConsoleApp\CapstoneConsoleApp\bin", options); driver.Manage().Window.Maximize(); // create default wait 100 seconds + set to ignore the most persistent and disruptive timeout errors that break scraper var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(100000)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException), typeof(WebDriverTimeoutException), typeof(UnhandledAlertException)); driver.Navigate().GoToUrl("https://login.yahoo.com/config/login?.src=finance&.intl=us&.done=https%3A%2F%2Ffinance.yahoo.com%2Fportfolios"); wait.Until(waiter => waiter.FindElement(By.Id("login-username"))); IWebElement username = driver.FindElement(By.Id("login-username")); username.SendKeys("*****@*****.**"); username.SendKeys(Keys.Return); // EXPLICIT WAIT wait.Until(waiter => waiter.FindElement(By.Id("login-passwd"))); IWebElement password = driver.FindElement(By.Id("login-passwd")); password.SendKeys("SILICONrhode1!"); IWebElement loginButton = driver.FindElement(By.Id("login-signin")); loginButton.SendKeys(Keys.Return); driver.Navigate().GoToUrl("https://finance.yahoo.com/portfolio/p_0/view/v1"); //EXPLICIT WAIT wait.Until(waiter => waiter.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[1]/td[13]/span"))); IWebElement list = driver.FindElement(By.TagName("tbody")); ReadOnlyCollection <IWebElement> items = list.FindElements(By.TagName("tr")); int count = items.Count; Console.WriteLine("Gathering Portfolio Data......................"); Console.WriteLine("There are " + count + " stocks in the list."); // create list to store stock data type List <Stock> stockList = new List <Stock>(); // print the contents of that list to the console Console.WriteLine("The Portfolio of stocks is as follows: "); //Loop iterate through portfolio of stocks, gathering data // current issue is the for (int i = 1; i <= count; i++) { string symbol = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[1]/a")).GetAttribute("innerText"); Console.WriteLine(symbol); string price = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[2]/span")).GetAttribute("innerText"); Console.WriteLine(price); string change = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[3]/span")).GetAttribute("innerText"); Console.WriteLine(change); string pchange = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[4]/span")).GetAttribute("innerText"); Console.WriteLine(pchange); string volume = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[7]/span")).GetAttribute("innerText"); Console.WriteLine(volume); string marketcap = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[13]/span")).GetAttribute("innerText"); Console.WriteLine(marketcap); string scrapeTime = driver.FindElement(By.XPath("//*[@id=\"pf-detail-table\"]/div[1]/table/tbody/tr[" + i + "]/td[6]/span")).GetAttribute("innerText"); Console.WriteLine(scrapeTime); // for each stock entry, a new stock object is created // the above data is set equal to the field within the object Stock newStock = new Stock(); newStock.Symbol = symbol; newStock.Price = price; newStock.Change = change; newStock.PChange = pchange; newStock.ScrapeTime = scrapeTime; newStock.Volume = volume; newStock.MarketCap = marketcap; // that stock is then added to the list of stocks stockList.Add(newStock); } driver.Quit(); return(stockList); }
/// <summary> /// Click a button that has a new dialog appear. Continuely click the button /// until the new dialog appears. /// </summary> /// <param name="caption">The caption of the dialog button</param> /// <param name="dialogId">The new dialog's unique id identifer. i.e. - 'RevenueBatchConstituentInbatchEditForm' /// If null is provided, then the method waits for a message box dialog that contains no unique id.</param> public static void ClickButton(string caption, string dialogId) { var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); waiter.Until(d => { ClickButton(caption); try { GetDisplayedElement( dialogId == null ? getXDialogByClass("bbui-dialog-msgbox") : getXDialogById(dialogId), 30); } catch (WebDriverTimeoutException) { return false; } return true; }); }
/// <summary> /// Waits the until element is no longer found. /// </summary> /// <example>Sample code to check page title: <code> /// this.Driver.WaitUntilElementIsNoLongerFound(dissapearingInfo, BaseConfiguration.ShortTimeout); /// </code></example> /// <param name="webDriver">The web driver.</param> /// <param name="locator">The locator.</param> /// <param name="timeout">The timeout.</param> public static void WaitUntilElementIsNoLongerFound(this IWebDriver webDriver, ElementLocator locator, double timeout) { var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(timeout)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException), typeof(NoSuchElementException)); //wait.Until(driver => webDriver.GetElements(locator).Count == 0); Need to change }
/// <summary> /// Check if a value exists as a selectable item in a dropdown list. /// </summary> /// <param name="xPath">The xPath of the dropdown. Advised to use Dialog.getXInput()</param> /// <param name="value">The value to check for as an option in the dropdown.</param> /// <returns>True if the value is an option, false otherwise.</returns> public static bool DropdownValueExists(string xPath, string value) { WebDriverWait waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); //click the arrow waiter.Until(d => { IWebElement element = d.FindElement(By.XPath(getXDropdownArrow(xPath))); if (element != null && element.Displayed && element.Enabled) { element.Click(); return true; } return false; }); //wait for the list to appear waiter.Until(d => { IWebElement dropdownList = d.FindElement(By.XPath(getXDropdownListItems)); if (dropdownList == null || !dropdownList.Displayed) return false; return true; }); //see if value exists in list. instead of iterating through all items, I could format an xPath and use the driver //without a waiter to find the element. if found, return true. if nosuchelement thrown, return false. ICollection<IWebElement> dropdownListItems = Driver.FindElements(By.XPath(getXDropdownListItems)); if (dropdownListItems.Count == 0) return false; else { foreach (IWebElement item in dropdownListItems) { if (item.Enabled && item.Text == value) return true; } } return false; }
public void TestMethod1() { driver = new ChromeDriver(); driver.Manage().Window.Maximize(); //driver.Url = "http://www.ankpro.com/"; driver.Url = "http://uitestpractice.com/students/Select"; wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5)); //Webdriver wait syntax wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); //webdriver ignore syntax fluentwait = new DefaultWait <IWebDriver>(driver); //Fluent wait syntax fluentwait.Timeout = TimeSpan.FromSeconds(5); //Fluent wait timeout fluentwait.PollingInterval = TimeSpan.FromMilliseconds(250); //fluent wait pollingInterval fluentwait.IgnoreExceptionTypes(typeof(NoSuchElementException)); fluentwait.Message = "Element not found"; //var login = wait.Until(ExpectedConditions.ElementToBeClickable(By.LinkText //("Log in"))); //login.Click();//Using webdriver wait to click login by linktext //var login = fluentwait.Until(z=> z.FindElement(By.LinkText //("Log in"))); //login.Click();//Using webdriver wait to click login by linktext //var checkbox = fluentwait.Until(m => m.FindElement(By.XPath //(".//*[starts-with(@id,'Rem')]"))); //checkbox.Click(); //bool selected = driver.FindElement(By.XPath(".//*[starts-with(@id,'Rem')]")).Selected; //bool selected = driver.FindElement(By.CssSelector("input[type=checkbox]:checked")).Selected; //Console.WriteLine(selected); //Console.WriteLine(selected); /*if (selected==true) * { * * Console.WriteLine("Checkbox is selected"); * * } * else if (selected==false) * { * Console.WriteLine("Checkbox is not selected"); * var checkbox = fluentwait.Until(x => x.FindElement(By.XPath * (".//*[starts-with(@id,'Rem')]"))); * checkbox.Click(); * Console.WriteLine("Checkbox is now selected"); * * } * * bool submitbtn = driver.FindElement(By.CssSelector("input[type=submit]")).Displayed; * if (submitbtn == true) * { * Console.WriteLine("Btn is displayed"); * } * else * { * Console.WriteLine("Btn not displayed"); * }*/ try { string choice = "China"; var element = fluentwait.Until(x => x.FindElement(By.Id("countriesSingle"))) .FindElements(By.TagName("option")); for (var i = 0; i < element.Count; i++) { element[i].Click(); Console.WriteLine(element[i].Text); if (element[i].Text == choice) { break; } } SelectElement Multiple = new SelectElement(driver.FindElement(By.Id("countriesMultiple"))); foreach (var option in Multiple.Options) { option.Click(); Console.WriteLine(option.Text); Thread.Sleep(1000); if (option.Text == "England") { break; } } } catch (Exception e) { Console.WriteLine(e.Message); throw; } finally { if (driver != null) { driver.Quit(); } } Thread.Sleep(3000); driver.Quit(); }
/// <summary> /// Set a Dropdown field. /// /// WebDriverTimeoutException is thrown if no value is found. /// </summary> /// <param name="xPath">The xPath to find the dropdown INPUT element with</param> /// <param name="value">The value to set the dropdown to.</param> public static void SetDropDown(string xPath, string value = "") { WaitClick(xPath); var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); waiter.Until(d => { var innerWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); innerWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); try { //click the dropdown arrow waiter.Until(d1 => { var dropdownArrow = d.FindElement(By.XPath(getXDropdownArrow(xPath))); if (dropdownArrow == null || !dropdownArrow.Displayed || !dropdownArrow.Enabled) return false; dropdownArrow.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } try { //wait for the list to appear waiter.Until(d2 => { var dropdownList = d.FindElement(By.XPath(getXDropdownListItems)); return dropdownList != null && dropdownList.Displayed; }); } catch (WebDriverTimeoutException) { return false; } try { //select the item in the list waiter.Until(d3 => { var dropdownItem = d.FindElement(By.XPath(getXDropdownItem(value))); if (dropdownItem == null || !dropdownItem.Displayed || !dropdownItem.Enabled) return false; dropdownItem.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } try { //send enter on the field waiter.Until(d4 => { var field = d.FindElement(By.XPath(xPath)); if (field == null || !field.Displayed) return false; field.SendKeys(Keys.Tab); return true; }); } catch (WebDriverTimeoutException) { return false; } try { //ensure the original grid value has been set before continuing ElementValueIsSet(xPath, value); } catch (WebDriverTimeoutException) { return false; } return true; }); }
public void Books_add_and_edit() { _driver.NavigateHome(); _driver.LoginAsLibrarian(); WebDriverWait wait = new WebDriverWait(_driver, System.TimeSpan.FromSeconds(15)); wait.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); wait.Until(driver => driver.FindElement(By.Id("navigate-books"))).Click(); // create new Book { wait.Until(driver => driver.FindElement(By.Id("books-add"))).Click(); wait.Until(driver => driver.FindElement(By.Id("titleInput"))).SendKeys("testBook"); wait.Until(driver => driver.FindElement(By.Id("isbn13Input"))).SendKeys("testIsbn"); wait.Until(driver => driver.FindElement(By.Id("authorInput"))).SendKeys("testAuthor"); wait.Until(driver => driver.FindElement(By.Id("descriptionInput"))).SendKeys("testDescription"); wait.Until(driver => driver.FindElement(By.Id("book-save"))).Click(); } Assert.Contains("Book changed successfully.", wait.Until(driver => driver.FindElement(By.Id("book-changed-alert"))).Text, StringComparison.InvariantCulture); // Assert that new book has correct values { wait.Until(driver => driver.FindElement(By.Id("book-changed-alert-link"))).Click(); Assert.Equal("testBook", wait.Until(driver => driver.FindElement(By.Id("titleInput"))).GetAttribute("value")); Assert.Equal("testIsbn", wait.Until(driver => driver.FindElement(By.Id("isbn13Input"))).GetAttribute("value")); Assert.Equal("testAuthor", wait.Until(driver => driver.FindElement(By.Id("authorInput"))).GetAttribute("value")); Assert.Equal("testDescription", wait.Until(driver => driver.FindElement(By.Id("descriptionInput"))).GetAttribute("value")); } // edit book { wait.Until(driver => driver.FindElement(By.Id("titleInput"))).ClearAndSendKeys("testBook X"); wait.Until(driver => driver.FindElement(By.Id("isbn13Input"))).ClearAndSendKeys("testIsbn X"); wait.Until(driver => driver.FindElement(By.Id("authorInput"))).ClearAndSendKeys("testAuthor X"); wait.Until(driver => driver.FindElement(By.Id("descriptionInput"))).ClearAndSendKeys("testDescription X"); wait.Until(driver => driver.FindElement(By.Id("book-save"))).Click(); } // Assert book was edited correctly { wait.Until(driver => driver.FindElement(By.Id("book-changed-alert-link"))).Click(); Assert.Equal("testBook X", wait.Until(driver => driver.FindElement(By.Id("titleInput"))).GetAttribute("value")); Assert.Equal("testIsbn X", wait.Until(driver => driver.FindElement(By.Id("isbn13Input"))).GetAttribute("value")); Assert.Equal("testAuthor X", wait.Until(driver => driver.FindElement(By.Id("authorInput"))).GetAttribute("value")); Assert.Equal("testDescription X", wait.Until(driver => driver.FindElement(By.Id("descriptionInput"))).GetAttribute("value")); } }
/// <summary> /// Set a grid cell's value using the searchlist. /// </summary> /// <param name="xPath">The xPath of the grid cell TD element.</param> /// <param name="searchDialogxPath">The xPath of the search dialog's field to set.</param> /// <param name="value">The value to set and use as search criteria in the specified search dialog field.</param> public static void SetGridSearchList(string xPath, string searchDialogxPath, string value) { var clickedWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); clickedWaiter.IgnoreExceptionTypes(typeof(StaleElementReferenceException)); clickedWaiter.Until(d1 => { try { //original field should be covered by the edit cell and therefore unclickable d1.FindElement(By.XPath(xPath)).Click(); return false; } catch (InvalidOperationException) { try { var innerWaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(5)); innerWaiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); //click the searchlist innerWaiter.Until(d => { var searchIcon = d.FindElement(By.XPath(getXGridEditCellSearchlist)); if (searchIcon == null || !searchIcon.Displayed || !searchIcon.Enabled) return false; searchIcon.Click(); return true; }); } catch (WebDriverTimeoutException) { return false; } return true; } }); var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); //search and select SetTextField(searchDialogxPath, value); SearchDialog.Search(); SearchDialog.SelectFirstResult(); //send enter on the edit grid waiter.Until(d => { //sometimes the original field is set and there is no need to send enter on the edit cell. //The value you search for may not be the associated display value of the selected item... var originalField = d.FindElement(By.XPath(xPath)); if (originalField.Displayed && (!String.IsNullOrWhiteSpace(originalField.Text) || !String.IsNullOrWhiteSpace(originalField.GetAttribute("value")))) return true; try { IWebElement editField = d.FindElement(By.XPath(getXGridEditCell)); if (editField == null || !editField.Displayed) return false; editField.SendKeys(Keys.Return); return true; } catch (NoSuchElementException) { return false; } }); //ensure the original grid value is not an empty string ElementValueIsNotNullOrEmpty(xPath); }
public static void DeleteAllPages(string name) { SearchPagesByName(name); IWebElement partSearchResultsLineElement; IWebElement selectAllCheckBoxElement; var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); wait.IgnoreExceptionTypes(typeof(InvalidOperationException), typeof(StaleElementReferenceException)); try { wait.Until(d => { partSearchResultsLineElement = Driver.FindElement(By.XPath(getXPagesSearchResultsLine)); selectAllCheckBoxElement = Driver.FindElement( By.XPath("//tr[contains(@class,'DataGridHeader')]//input[contains(@type,'checkbox')]")); if (selectAllCheckBoxElement == null || partSearchResultsLineElement.Displayed == false || partSearchResultsLineElement.Text.Contains("No")) { return(false); } WaitClick("//tr[contains(@class,'DataGridHeader')]//input[contains(@type,'checkbox')]"); WaitClick(getXDeleteButton); var innerwaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); innerwaiter.IgnoreExceptionTypes(typeof(NoAlertPresentException)); innerwaiter.Until(dd => { IAlert alert = Driver.SwitchTo().Alert(); alert.Accept(); return(true); }); return(true); }); } catch (WebDriverException) { } // Need to check enabled first for this one !! GetEnabledElement("//div[contains(@class,'ExplorerTabs')]//td[./text()='Folders']"); WaitClick("//div[contains(@class,'ExplorerTabs')]//td[./text()='Folders']"); WaitClick("//span[./text()='Deleted Pages/Templates']"); GetDisplayedElement("//div[contains(@class,'ExplorerPath')]//span[./text()='Deleted Pages/Templates']"); wait.Until(d => { partSearchResultsLineElement = Driver.FindElement(By.XPath(getXPagesSearchResultsLine)); selectAllCheckBoxElement = Driver.FindElement(By.XPath("//tr[contains(@class,'DataGridHeader')]//input[contains(@type,'checkbox')]")); if (selectAllCheckBoxElement == null || partSearchResultsLineElement.Displayed == false || partSearchResultsLineElement.Text.Contains("No")) { return(false); } WaitClick("//tr[contains(@class,'DataGridHeader')]//input[contains(@type,'checkbox')]"); WaitClick(getXDeleteButton); var innerwaiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(10)); innerwaiter.IgnoreExceptionTypes(typeof(NoAlertPresentException)); innerwaiter.Until(dd => { IAlert alert = Driver.SwitchTo().Alert(); alert.Accept(); return(true); }); return(true); }); }
/// <summary> /// Expand a tree node if it is collapsed. /// </summary> public static void ExpandNode(string xPath) { var waiter = new WebDriverWait(Driver, TimeSpan.FromSeconds(TimeoutSecs)); waiter.IgnoreExceptionTypes(typeof(InvalidOperationException)); waiter.Until(d => { var node = GetEnabledElement(xPath); var nodeClass = node.GetAttribute("class"); if (nodeClass.Contains("plus")) { node.Click(); WaitForNodesToLoad(xPath); } else { WaitClick(xPath + "/.."); } return true; }); }
public Base_Page(RemoteWebDriver driver) { webDriver = driver; wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(2)); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); }