private WebElement cyleFindElement(List<By> byList) { WebElement webEle = null; for (By by : byList) { try { webEle = findElement(by); } catch (NoSuchElementException e) { } if (webEle != null) { return webEle; } } return null; }
/** * Returns a 'wait' proxy that determines if an element is either hidden or non-existent. * * @param locator web element locator * @return 'true' if the element is hidden or non-existent; otherwise 'false' */ public static Coordinator<Boolean> invisibilityOfElementLocated(final By locator) { return new Coordinator<Boolean>() { @Override public Boolean apply(SearchContext context) { try { return !(context.findElement(locator).isDisplayed()); } catch (NoSuchElementException | StaleElementReferenceException e) { // NoSuchElementException: The element is not present in DOM. // StaleElementReferenceException: Implies that element no longer exists in the DOM. return true; } } @Override public String toString() { return "element to no longer be visible: " + locator; } }; }
public void CheckStickers() { // find number of ducks on main page int n = driver.findElements(By.cssSelector("[class=image-wrapper]")).size(); System.out.println("Number of products available:" + n); driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); if (n > 0) { products = driver.findElements(By.cssSelector("[class=image-wrapper]")); driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); int i = 0; while (i < n){ System.out.print("Duck" + (i+1) + " has a sticker: "); //if sticker is available it will be printed, otherwise the message about error will be printed. try { System.out.println(products.get(i).findElement(By.cssSelector("[class^=sticker]")).getText()); } catch (NoSuchElementException ex) { System.out.println("Error! No sticker found."); } i++; } } }
/** * select a value * * @param value the value to select */ @Override @PublicAtsApi public void setValue( String value ) { new RealHtmlElementState(this).waitToBecomeExisting(); try { WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); select.selectByVisibleText(value); } catch (NoSuchElementException nsee) { throw new SeleniumOperationException("Option with label '" + value + "' not found. (" + this.toString() + ")"); } UiEngineUtilities.sleep(); }
/** * set the single selection value * * @param value the value to select */ @Override @PublicAtsApi public void setValue( String value ) { new RealHtmlElementState(this).waitToBecomeExisting(); try { WebElement element = RealHtmlElementLocator.findElement(this); Select select = new Select(element); select.selectByVisibleText(value); } catch (NoSuchElementException nsee) { throw new SeleniumOperationException("Option with label '" + value + "' not found. (" + this.toString() + ")"); } UiEngineUtilities.sleep(); }
@Override public Boolean get() { return SeleniumUtils.retryOnStale(() -> { try { WebElement element = component.element(); if (shouldBeVisible) { return element != null && element.isDisplayed(); } return element == null || !element.isDisplayed(); } catch (NoSuchElementException e) { return shouldBeVisible ? false : true; } }); }
/** * Returns true if the component is selected. Waits {@link SeleniumGlobals#getShortTimeoutInSeconds()} seconds for * the component to become available. * * @return true if selected */ default boolean isSelected() { try { return SeleniumUtils.retryOnStale(() -> { WebElement element = element(); return element.isSelected(); }); } catch (NoSuchElementException e) { return false; } }
/** * Returns true if the component is editable. Waits {@link SeleniumGlobals#getShortTimeoutInSeconds()} seconds for * the component to become available. * * @return true if editable */ default boolean isEditable() { try { return SeleniumUtils.retryOnStale(() -> { WebElement element = element(); return element.isDisplayed() && element.isEnabled(); }); } catch (NoSuchElementException e) { return false; } }
/** * Returns true if the component is enabled. Waits {@link SeleniumGlobals#getShortTimeoutInSeconds()} seconds for * the component to become available. * * @return true if enabled */ default boolean isEnabled() { try { return SeleniumUtils.retryOnStale(() -> { WebElement element = element(); return element.isEnabled(); }); } catch (NoSuchElementException e) { return false; } }
/** * Returns true if a {@link WebElement} described by this component is visible. By default it checks, if the element * is visible. This method has no timeout, it does not wait for the component to become existent. * * @return true if the component is visible */ default boolean isVisible() { try { return SeleniumUtils.retryOnStale(() -> { WebElement element = element(); return element.isDisplayed(); }); } catch (NoSuchElementException e) { return false; } }
public void clear() { try { List<WebElement> removeButtons = searchContext().findElements(By.className("remove-button")); for (WebElement removeButton : removeButtons) { removeButton.click(); } } catch (NoSuchElementException e) { //Nothing to do. May be empty } }
public RemoteWebElement findElementByXpath(String xpath) throws Exception { String f = "(function(xpath, element) { var result = " + JsAtoms.xpath("xpath", "element") + ";" + "return result;})"; JsonObject response = getInspectorResponse( f, false, callArgument().withValue(xpath), callArgument().withObjectId(getRemoteObject().getId())); RemoteObject ro = inspector.cast(response); if (ro == null) { throw new NoSuchElementException("cannot find element by Xpath " + xpath); } else { return ro.getWebElement(); } }
/** * Enters the specified text into the field, within the specified fieldset. * @param text The text to enter * @param fieldLabel The field label * @param fieldsetLabel The fieldset label */ public void enterIntoFieldInFieldset(String text, String fieldLabel, String fieldsetLabel) { WebElement fieldsetElement; try { // find the fieldset with the fieldset label fieldsetElement = webDriver.findElement( By.xpath("//label[contains(text(),'" + fieldsetLabel + "')]/ancestor::fieldset[1]")); } catch (NoSuchElementException noSuchElement) { fieldsetElement = findFieldsetByLegend(fieldsetLabel); } // find the specified label (with the for="id" attribute)... WebElement labelElement = fieldsetElement.findElement( By.xpath(".//label[contains(text(),'" + fieldLabel + "')]")); // find the text element with id matching the for attribute // (search in the fieldset rather than the whole page, to get around faulty HTML where id's aren't unique!) WebElement textElement = fieldsetElement.findElement(By.id(labelElement.getAttribute("for"))); textElement.clear(); textElement.sendKeys(text); }
/** * Selects the specified radio button. Supports well-formed labels and radio buttons nested inside the label. * @param labelText The radio button label */ public void selectRadio(String labelText) { try { // find the input associated with the specified (well-formed) label... WebElement labelElement = webDriver.findElement(By.xpath("//label[contains(text(),'" + labelText + "')]")); webDriver.findElement(By.id(labelElement.getAttribute("for"))).click(); } catch (NoSuchElementException | IllegalArgumentException ex) { webDriver.findElements(By.tagName("label")).stream() .filter((l) -> l.getText().contains(labelText)) // label with text .map((l) -> l.findElement(By.xpath("./input[@type = 'radio']"))) // nested radio .findFirst().orElseThrow(() -> { String message = "No radio button found with label (well-formed or nested): " + labelText; logger.error(message); return new IllegalArgumentException(message); }).click(); } }
/** * Finds the specified checkbox button. Supports well-formed labels and inputs nested inside the label. * @param labelText The checkbox button label */ private WebElement findCheckbox(String labelText) { try { // find the input associated with the specified (well-formed) label... WebElement labelElement = webDriver.findElement(By.xpath("//label[contains(text(),'" + labelText + "')]")); return webDriver.findElement(By.id(labelElement.getAttribute("for"))); } catch (NoSuchElementException | IllegalArgumentException ex) { return webDriver.findElements(By.tagName("label")).stream() .filter((label) -> label.getText().contains(labelText)) // label with text .map((label) -> label.findElement(By.xpath("./input[@type = 'checkbox']"))) // nested checkbox .findFirst().orElseThrow(() -> { String message = "No checkbox button found with label (well-formed or nested): " + labelText; logger.error(message); return new IllegalArgumentException(message); }); } }
/** * Checks whether a table, identified by having a heading with the specified text, has at least the specified * number of rows (ignoring any heading rows). * @param headingText The table heading text to look for * @param rows The minimum number of rows the table must have * @return <code>true</code> if the table has at least <code>rows</code> rows. */ public boolean checkTableHasRows(String headingText, int rows) { try { // find the table with a heading containing the specified text... WebElement tableElement = webDriver.findElement( By.xpath("//th[contains(text(),'" + headingText + "')]//ancestor::table[1]")); // then count the number of rows in the table... List<WebElement> rowElements = tableElement.findElements(By.tagName("tr")); // is the number of rows (minus the heading row) at lest the specified amount? return (rowElements.size() - 1) >= rows; } catch (NoSuchElementException ex) { return false; } }
public static void waitFor(WebDriver driver, long timeout, By... elements) throws TimeoutException, InterruptedException { try { WaitUtil.waitFor(() -> elementsPresent(driver, elements), null, 1000L, timeout); } catch (TimeoutException ex) { try { for (By element : elements) { WebElement webElement = driver.findElement(element); if (!webElement.isDisplayed()) { throw new TimeoutException("Timeout exception during waiting for web element: " + webElement.getText()); } } } catch (NoSuchElementException | StaleElementReferenceException x) { throw new TimeoutException("Timeout exception during waiting for web element: " + x.getMessage()); } } }
/** * Wait for element to appear. * * @param driver the driver * @param element the element * @param logger the logger */ public static boolean waitForElementToAppear(WebDriver driver, WebElement element, ExtentTest logger) { boolean webElementPresence = false; try { Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver).pollingEvery(2, TimeUnit.SECONDS) .withTimeout(60, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); fluentWait.until(ExpectedConditions.visibilityOf(element)); if (element.isDisplayed()) { webElementPresence= true; } } catch (TimeoutException toe) { logger.log(LogStatus.ERROR, "Timeout waiting for webelement to be present<br></br>" + toe.getStackTrace()); } catch (Exception e) { logger.log(LogStatus.ERROR, "Exception occured<br></br>" + e.getStackTrace()); } return webElementPresence; }
protected void waitForElements(BasePage page, final WebElement... elements) { new WebDriverWait(getDriverProxy(), 40) .withMessage("Timed out navigating to [" + page.getClass().getName() + "]. Expected elements were not found. See screenshot for more details.") .until((WebDriver d) -> { for (WebElement elm : elements) { try { elm.isDisplayed(); } catch (NoSuchElementException e) { // This is expected exception since we are waiting for the selenium element to come into existence. // This method will be called repeatedly until it reaches timeout or finds all selenium given. return false; } } return true; }); }
protected void waitForElements(BasePage page, final By... elements) { new WebDriverWait(getDriverProxy(), 40) .withMessage("Timed out navigating to [" + page.getClass().getName() + "]. Expected selenium elements were not found. See screenshot for more details.") .until((WebDriver d) -> { boolean success = true; for (By elm : elements) { List<WebElement> foundElements = d.findElements(elm); if (!foundElements.isEmpty()) { try { ((WebElement) foundElements.get(0)).isDisplayed(); } catch (NoSuchElementException e) { // This is expected exception since we are waiting for the selenium element to come into existence. // This method will be called repeatedly until it reaches timeout or finds all selenium given. success = false; break; } } else { success = false; break; } } return success; }); }
public static void waitUntillElementToBeClickable(int TotalTimeInSeconds, int PollingTimeInMilliseconds, WebElement Element) { FluentWait<WebDriver> ClickableWait = new FluentWait<WebDriver>(getWebDriver()) .withTimeout(TotalTimeInSeconds, TimeUnit.SECONDS) .pollingEvery(PollingTimeInMilliseconds, TimeUnit.MILLISECONDS) .ignoring(NoSuchElementException.class); ClickableWait.until(ExpectedConditions.elementToBeClickable(Element)); }
private void clickButton(final String buttonLabel) { final WebElement button = bobcatWait.withTimeout(Timeouts.BIG).until(input -> window.findElement( By.xpath(String.format(BUTTON_XPATH_FORMATTED, buttonLabel)))); bobcatWait.withTimeout(Timeouts.MEDIUM).until(ExpectedConditions.elementToBeClickable(button)); bobcatWait.withTimeout(Timeouts.BIG).until(input -> { boolean confirmationWindowClosed; try { button.click(); confirmationWindowClosed = !window.isDisplayed(); } catch (NoSuchElementException | StaleElementReferenceException e) { LOG.debug("Confirmation window is not available", e); confirmationWindowClosed = true; } return confirmationWindowClosed; }); }
/** * Clicks the selected option in the context menu and waits until context menu disappears. * * @param option option to click * @return this context menu object */ public AemContextMenu clickOption(final MenuOption option) { bobcatWait.withTimeout(Timeouts.BIG).until(input -> { try { currentScope.findElement( By.xpath(String.format(MENU_OPTION_XPATH, XpathUtils.quote(option.getLabel())))) .click(); currentScope.isDisplayed(); return Boolean.FALSE; } catch (NoSuchElementException e) { LOG.debug("MenuOption is not present: ", e); return Boolean.TRUE; } }); return this; }
private void signupUser() { goToLogin(); try { final String migrationLightboxSelector = "#migration_lightbox"; final FluentWebElement migrationLightbox = browser.findFirst(migrationLightboxSelector); migrationLightbox.find(".mfp-close").click(); browser.await().atMost(5L, TimeUnit.SECONDS).until(migrationLightboxSelector).areNotDisplayed(); } catch(final NoSuchElementException nsee) { // migration lightbox was not shown, so we do not need to close it } browser.fill("input", withName("email")).with(EVENTBRITE_USER_EMAIL); browser.fill("input", withName("password")).with(System.getenv("EVENTBRITE_USER_PASSWORD")); browser.find("input", with("value").equalTo("Log in")).click(); browser.await().untilPage().isLoaded(); browser.await().atMost(5, TimeUnit.SECONDS).until("#access_choices_allow").areEnabled(); browser.find("#access_choices_allow").click(); browser.await().untilPage().isLoaded(); }
private static void generateMarkLinkHashMap(WebDriver webDriver, List<WebElement> markList, Hashtable<String, String> dictMarkLink) { for (WebElement element : markList) { WebElement hrefLink; String markLink = webDriver.getCurrentUrl(); try { hrefLink = element.findElement(By.tagName("a")); markLink = hrefLink.getAttribute(PageLoaderHelper.HYPER_REFERENCE_ATTRIBUTE_TAG); } catch (NoSuchElementException e) { //In this case, subMenu has already been selected, the current link is then the mark link hrefLink = element.findElement(By.tagName("span")); } String markNameText = hrefLink.getText().toUpperCase(); dictMarkLink.put(markNameText, markLink); } }
/** * Find the element. */ public WebElement findElement() { if (cachedElement != null && shouldCache) { return cachedElement; } List<WebElement> result = waitFor(); if (result.size() == 0) { String message = "Can't locate an element by this strategy: " + by.toString(); if (waitingFunction.foundStaleElementReferenceException != null) { throw new NoSuchElementException(message, waitingFunction.foundStaleElementReferenceException); } throw new NoSuchElementException(message); } if (shouldCache) { cachedElement = result.get(0); } return result.get(0); }
/** * Get column index from a column name * Or several strings in a cell in first row that can determine a unique column * which separated by "," * @throws Exception * * @param String * Example: getColumnIndex("ColumnName"), getColumnIndex("namestring1, namestring2") * * */ public int getColumnIndex(String columnName){ String[] columnkey = columnName.split(","); StringBuilder sColumnXpath = new StringBuilder(".//tr/th"); for(int i=0;i<columnkey.length;i++) { sColumnXpath.append("[contains(.,'").append(columnkey[i]).append("')]"); } sColumnXpath.append(columnFilter); if(table.findElements(By.xpath(".//tr/th")).size()==0) { throw new NoSuchElementException("column name is not under tag <th>"); } return table.findElement(By.xpath(sColumnXpath.toString())).findElements(By.xpath("./preceding-sibling::th" + columnFilter)).size() + 1; }
/** * 文本框输入操作 * @param locator 元素locator * @param value 输入值 */ public void type(Locator locator,String value) { try { WebElement webElement=findElement(locator); webElement.sendKeys(value); log.info("input输入:"+locator.getLocalorName()+"["+"By."+locator.getBy()+":"+locator.getElement()+"value:"+value+"]"); } catch (NoSuchElementException e) { // TODO: handle exception log.error("找不到元素,input输入失败:"+locator.getLocalorName()+"["+"By."+locator.getBy()+":"+locator.getElement()+"]"); e.printStackTrace(); //throw e; //Assertion.flag=false; } }
/** * 选择下拉框操作 * @param locator 元素locator * @param text 选择下拉值 */ public void selectByText(Locator locator,String text) { try { WebElement webElement=findElement(locator); Select select=new Select(webElement); log.info("选择select标签:"+locator.getLocalorName()+"["+"By."+locator.getBy()+":"+locator.getElement()+"]"); try { //select.selectByValue(value); select.selectByVisibleText(text); log.info("选择下拉列表项:" + text); } catch (NoSuchElementException notByValue) { // TODO: handle exception log.info("找不到下拉值,选择下拉列表项失败 " + text); throw notByValue; } } catch (NoSuchElementException e) { // TODO: handle exception log.error("找不到元素,选择select标签失败:"+locator.getLocalorName()+"["+"By."+locator.getBy()+":"+locator.getElement()+"]"); throw e; } }
@Override public WebElement find() { try { return driver != null ? driver.findElements(by).get(index) : searchContext.domElements(by).get(index).getWrappedWebElement(); } catch (IndexOutOfBoundsException e) { throw new NoSuchElementException("Unable to find element with locator " + by + " and index " + index + ", Exception - " + e); } }
@Override public void selectByText(final String text, final String errorMessage) { try { selectByText(text); } catch (NoSuchElementException e) { Reporter.log("ERROR: " + errorMessage); throw new AssertionError(e); } }
@Override public void selectByIndex(final int index, final String errorMessage) { try { selectByIndex(index); } catch (NoSuchElementException e) { Reporter.log("ERROR: " + errorMessage); throw new AssertionError(e); } }
@Override public void selectByValue(final String value, final String errorMessage) { try { selectByValue(value); } catch (NoSuchElementException e) { Reporter.log("ERROR: " + errorMessage); throw new AssertionError(e); } }
@Test public void testPropagate() { ExamplePage page = getPage(); try { getMetaTagNamed(page.getDriver(), "test"); fail("No exception was thrown"); } catch (NoSuchElementException e) { assertTrue(e.getMessage().startsWith("No meta element found with name: ")); } }
public void invalidTabIndex() throws Throwable { driver = new JavaDriver(); WebElement tab = driver.findElement(By.cssSelector("tabbed-pane::nth-tab(10)")); try { tab.click(); throw new MissingException(NoSuchElementException.class); } catch (NoSuchElementException e) { } }
public void indexOutOfBoundException() throws Throwable { driver = new JavaDriver(); try { WebElement findElement = driver.findElement(By.cssSelector("list::nth-item(6)")); findElement.click(); throw new MissingException(NoSuchElementException.class); } catch (NoSuchElementException e) { } }
public void listThrowsNSEWhenIndexOutOfBounds() throws Throwable { driver = new JavaDriver(); try { WebElement findElement = driver.findElement(By.cssSelector("#list-1::nth-item(31)")); findElement.click(); throw new MissingException(NoSuchElementException.class); } catch (NoSuchElementException e) { } }
public void findElementThrowsNoSuchElementIfNotFound() throws Throwable { driver = new JavaDriver(); SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { frame.setLocationRelativeTo(null); frame.setVisible(true); } }); try { driver.findElement(By.name("click-me-note-there")); throw new MissingException(NoSuchElementException.class); } catch (NoSuchElementException e) { } }
public void gettableCellNonexistant() throws Throwable { driver = new JavaDriver(); WebElement errCell = driver.findElement(By.cssSelector("table::mnth-cell(20,20)")); try { errCell.getText(); throw new MissingException(NoSuchElementException.class); } catch (NoSuchElementException e) { } }
public void tableCellEditUneditable() throws Throwable { driver = new JavaDriver(); try { WebElement cell = driver.findElement(By.cssSelector("table::mnth-cell(3,1)::editor")); cell.sendKeys("Hello World", Keys.ENTER); throw new MissingException(NoSuchElementException.class); } catch (NoSuchElementException e) { } }