Java Code Examples for org.openqa.selenium.NoSuchElementException

The following are top voted examples for showing how to use org.openqa.selenium.NoSuchElementException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: POM_HYBRID_FRAMEOWRK   File: WebUtilities.java   Source Code and License 7 votes vote down vote up
/**
 * 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;
}
 
Example 2
Project: phoenix.webui.framework   File: CyleSearchStrategy.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 3
Project: Selenium-Foundation   File: Coordinators.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
        }
    };
}
 
Example 4
Project: ats-framework   File: RealHtmlMultiSelectList.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 5
Project: ats-framework   File: RealHtmlSingleSelectList.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
}
 
Example 6
Project: selenium-components   File: SeleniumConditions.java   Source Code and License 6 votes vote down vote up
@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;
        }

    });
}
 
Example 7
Project: selenium-components   File: SelectableSeleniumComponent.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 8
Project: selenium-components   File: EditableSeleniumComponent.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 9
Project: selenium-components   File: EditableSeleniumComponent.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 10
Project: selenium-components   File: VisibleSeleniumComponent.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 11
Project: selenium-components   File: TagsInputComponent.java   Source Code and License 6 votes vote down vote up
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
    }
}
 
Example 12
Project: mot-automated-testsuite   File: WebDriverWrapper.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 13
Project: mot-automated-testsuite   File: WebDriverWrapper.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
    }
}
 
Example 14
Project: mot-automated-testsuite   File: WebDriverWrapper.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
                });
    }
}
 
Example 15
Project: mot-automated-testsuite   File: WebDriverWrapper.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
    }
}
 
Example 16
Project: xtf   File: DriverUtil.java   Source Code and License 6 votes vote down vote up
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());
		}
	}
}
 
Example 17
Project: AutomationFrameworkTPG   File: BasePage.java   Source Code and License 6 votes vote down vote up
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;
	});
}
 
Example 18
Project: AutomationFrameworkTPG   File: BasePage.java   Source Code and License 6 votes vote down vote up
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;
	});
}
 
Example 19
Project: WebAutomation_AllureParallel   File: FluentWaiting.java   Source Code and License 6 votes vote down vote up
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));
}
 
Example 20
Project: bobcat   File: ConfirmationWindow.java   Source Code and License 6 votes vote down vote up
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;
  });
}
 
Example 21
Project: bobcat   File: AemContextMenu.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
}
 
Example 22
Project: songs_play   File: EventbriteOAuth2Test.java   Source Code and License 6 votes vote down vote up
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();
}
 
Example 23
Project: vpMaster   File: SubMenuPageLoader.java   Source Code and License 6 votes vote down vote up
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);
   }
}
 
Example 24
Project: menggeqa   File: AppiumElementLocator.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
}
 
Example 25
Project: PatatiumWebUi   File: TableElement.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
	
}
 
Example 26
Project: PatatiumWebUi   File: ElementAction.java   Source Code and License 6 votes vote down vote up
/**
 * 文本框输入操作
 * @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;
	}

}
 
Example 27
Project: PatatiumWebUi   File: ElementAction.java   Source Code and License 6 votes vote down vote up
/**
 * 选择下拉框操作
 * @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;
	}
}
 
Example 28
Project: teasy   File: FindElementsLocator.java   Source Code and License 5 votes vote down vote up
@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);
    }
}
 
Example 29
Project: teasy   File: SelectImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void selectByText(final String text, final String errorMessage) {
    try {
        selectByText(text);
    } catch (NoSuchElementException e) {
        Reporter.log("ERROR: " + errorMessage);
        throw new AssertionError(e);
    }
}
 
Example 30
Project: teasy   File: SelectImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void selectByIndex(final int index, final String errorMessage) {
    try {
        selectByIndex(index);
    } catch (NoSuchElementException e) {
        Reporter.log("ERROR: " + errorMessage);
        throw new AssertionError(e);
    }
}
 
Example 31
Project: teasy   File: SelectImpl.java   Source Code and License 5 votes vote down vote up
@Override
public void selectByValue(final String value, final String errorMessage) {
    try {
        selectByValue(value);
    } catch (NoSuchElementException e) {
        Reporter.log("ERROR: " + errorMessage);
        throw new AssertionError(e);
    }
}
 
Example 32
Project: Selenium-Foundation   File: JsUtilityTest.java   Source Code and License 5 votes vote down vote up
@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: "));
    }
}
 
Example 33
Project: marathonv5   File: JTabbedPaneTest.java   Source Code and License 5 votes vote down vote up
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) {
    }
}
 
Example 34
Project: marathonv5   File: JListTest.java   Source Code and License 5 votes vote down vote up
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) {
    }
}
 
Example 35
Project: marathonv5   File: JListXTest.java   Source Code and License 5 votes vote down vote up
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) {
    }
}
 
Example 36
Project: marathonv5   File: JavaDriverTest.java   Source Code and License 5 votes vote down vote up
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) {
    }
}
 
Example 37
Project: marathonv5   File: JTableTest.java   Source Code and License 5 votes vote down vote up
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) {
    }
}
 
Example 38
Project: marathonv5   File: JTableTest.java   Source Code and License 5 votes vote down vote up
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) {
    }
}
 
Example 39
Project: autotest   File: WebTestBase.java   Source Code and License 5 votes vote down vote up
/**
 * 判断元素是否存在
 *
 * @param webElement
 * @return
 */
public boolean isElementExist(WebElement webElement) {
    try {
        webElement.isEnabled();
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}
 
Example 40
Project: saladium   File: SaladiumDriver.java   Source Code and License 5 votes vote down vote up
@Override
public void selectionner(String type, String selector, String valeur) {
    this.logger.info("selectionner(type" + type + ", selector" + selector + ", valeur" + valeur + ")");
    try {
        By locator = BySelec.get(type, selector);
        WebElement elem = wait.until(ExpectedConditions.presenceOfElementLocated(locator));
        String tagName = elem.getTagName();
        if (tagName.equals("select")) {
            Select select = new Select(elem);
            // List<WebElement> options = select.getAllSelectedOptions();
            // Iterator<WebElement> it = options.iterator();
            // while (it.hasNext()) {
            // WebElement webElement = it.next();
            // if ("auto".equals(webElement.getCssValue("z-index"))) {
            // if (!webElement.isDisplayed()) {
            // System.out.println("################### !isDisplayed()");
            // }
            // System.out.println("################### cssValue " + webElement.getCssValue("z-index"));
            // }
            // }
            select.selectByVisibleText(valeur);
            // Thread.sleep(1000);
        } else {
            elem.click();
            List<WebElement> children = elem.findElements(
                By.xpath("//div[@class='listComboBoxElement']/li"));
            Iterator<WebElement> it = children.iterator();
            boolean flag = false;
            do {
                WebElement webElement = it.next();
                if (webElement.getText().startsWith(valeur)) {
                    if (webElement.isDisplayed()) {
                        webElement.click();
                        flag = true;
                    }
                }
            } while (!flag && it.hasNext());
            if (!flag) {
                Assert.fail("Impossible de trouver la valeur :" + valeur
                    + " pour le champs :" + type + ":" + selector);
            }
        }
    } catch (NoSuchElementException | TimeoutException e) {
        String pathScreenShot = takeScreenShot();
        Assert.fail("Sélection impossible ! (type" + type + ", selector" + selector + ", valeur" + valeur + ") pathScreenShot=" + pathScreenShot);
    }
}
 
Example 41
Project: SeWebDriver_Homework   File: StickersTest.java   Source Code and License 5 votes vote down vote up
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++;
        }
    }
}
 
Example 42
Project: SeWebDriver_Homework   File: GeoZonesSortingTest.java   Source Code and License 5 votes vote down vote up
public void DisplayGeoZones() {
    // check if menu is displayed
    try {
        driver.findElement(By.className("list-vertical")).isDisplayed();
        driver.findElement(By.linkText("Geo Zones")).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        // read header text
        String header_text = driver.findElement(By.xpath("//h1[contains(text(),Text)]")).getText();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        System.out.print("Menu line '" + header_text + "' opened. Number of Geo Zones found: ");

        //read list of Geo Zones if it's available
        if (driver.findElement(By.name("geo_zones_form")).isDisplayed()) {
            geozones = driver.findElements(By.className("row"));
            int n = driver.findElements(By.className("row")).size();
            String[] ms2 = new String[n];
            System.out.println(n);
            for (int i = 0; i < n; i++) {
                ms2[i] = geozones.get(i).getAttribute("textContent").substring(16,29).toString().replaceAll("[^A-Za-zА-Яа-я]", "");
                System.out.println("Geo Zone:" + ms2[i]);
                geozones.get(i).findElement(By.className("fa-pencil")).click();
                driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                DisplayCountryZones();
                geozones = driver.findElements(By.className("row"));
            }
            //validate if sorting of Geo Zones is also ok
            SortingTest(ms2, n);
        }

    } catch (NoSuchElementException ex) {
        //exception will be raised if no menu displayed.
        throw ex;
    }
}
 
Example 43
Project: SeWebDriver_Homework   File: CountriesSortingTest.java   Source Code and License 5 votes vote down vote up
public void DisplayCountries() {
    // check if menu is displayed
    try {
        driver.findElement(By.className("list-vertical")).isDisplayed();
        driver.findElement(By.linkText("Countries")).click();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        // read header text
        String header_text = driver.findElement(By.xpath("//h1[contains(text(),Text)]")).getText();
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
        System.out.print("Menu line '" + header_text + "' opened. Number of countries found: ");

        //read list of countries if it's available
        if (driver.findElement(By.name("countries_form")).isDisplayed()) {
            countries = driver.findElements(By.className("row"));
            int n = driver.findElements(By.className("row")).size();
            System.out.println(n);
            String[][] ms = new String[n][4];
            String[] ms1 = new String [n];
            for (int i=0; i < n; i++) {
                String row = countries.get(i).getAttribute("textContent").toString().replaceAll("[^A-Za-zА-Яа-я0-9]", "");
               // System.out.print("##" + row); //not parsed rows

                //Parse textContent to create array of strings
                int r_length = row.length();
                ms[i][0] = row.substring(0,3).replaceAll("[^0-9]",""); //number
                ms[i][1] = row.substring(1,5).replaceAll("[^A-ZА-Я]", "").substring(0,2); //country code
                ms[i][2] = row.substring(1,r_length).replaceAll("[^A-Za-zА-Яа-я]", "").substring(2); //country name
                ms1[i] = ms[i][2];
                ms[i][3] = row.substring(r_length-2,r_length).replaceAll("[^0-9]",""); //zones
               System.out.println(".  Parsed Data: " + ms[i][0] + "/ " + ms[i][1] + " /" + ms[i][2] + "/ " + ms[i][3]);
                //Check Zones sorting
                if (ms[i][3].equalsIgnoreCase("0" ) == false) {
                    countries.get(i).findElement(By.className("fa-pencil")).click();
                    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                    DisplayZones ();
                    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                    //reinitialize countries List to avoid Stale element exception
                    countries = driver.findElements(By.className("row"));
                }
               }
            System.out.println("End of list.");
            //validate if sorting of countries is ok
            SortingTest(ms1, n);
            }
        } catch (NoSuchElementException ex) {
        //exception will be raised if no menu displayed.
        throw ex;
    }
}
 
Example 44
Project: SeWebDriver_Homework   File: AuthorizationTest.java   Source Code and License 5 votes vote down vote up
public void Buy_Something() {
    //buy something in the shop
    driver.findElement(By.className("image-wrapper")).click();
    //buy 101 ducks
    driver.findElement(By.name("quantity")).sendKeys("10");
    //select size if available
    try {
        qchk = driver.findElement(By.name("options[Size]")).isDisplayed();
        driver.findElement(By.name("options[Size]")).sendKeys("Small");
    }  catch (NoSuchElementException ex) {
        System.out.println ("No size selection is available");
    }
    driver.findElement(By.name("add_cart_product")).click();
}
 
Example 45
Project: selenium-components   File: SeleniumConditions.java   Source Code and License 5 votes vote down vote up
@Override
public Boolean get()
{
    try
    {
        WebElement element = component.element();

        return text.equals(element.getText());
    }
    catch (NoSuchElementException e)
    {
        return false;
    }
}
 
Example 46
Project: selenium-components   File: AbstractSeleniumPage.java   Source Code and License 5 votes vote down vote up
@Override
public final WebElement element() throws NoSuchElementException
{
    try
    {
        return SeleniumUtils.keepTrying(SeleniumGlobals.getLongTimeoutInSeconds(),
            () -> selector.find(environment.getDriver()));
    }
    catch (Exception e)
    {
        throw new NoSuchElementException(selector.decribe(null), e);
    }
}
 
Example 47
Project: selenium-components   File: AbstractSeleniumComponent.java   Source Code and License 5 votes vote down vote up
@Override
public WebElement element() throws NoSuchElementException
{
    try
    {
        return SeleniumUtils.keepTrying(SeleniumGlobals.getShortTimeoutInSeconds(),
            () -> selector.find(parent.searchContext()));
    }
    catch (Exception e)
    {
        throw new NoSuchElementException(selector.decribe(parent.describe()), e);
    }
}
 
Example 48
Project: devtools-driver   File: ExampleMobileSafariWebTest.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  // Create a DesiredCapabilities object to request specific devices from the WebDriver server.
  // A udid can be optionally specified, otherwise an arbitrary device is chosen.
  DesiredCapabilities caps = new DesiredCapabilities();
  // caps.setCapability("uuid", udid);
  // Start a WebDriver session. The local machine has to be running the SafariDriverServer, or
  // change localhost below to an IP running the SafariDriverServer.
  driver = new RemoteWebDriver(new URL("http://localhost:5555/wd/hub"), caps);
  // Connect to a URL
  driver.get("http://www.google.com");

  // Interact with the web page. In this example use case, the Webdriver API is used to find
  // specific elements, test a google search and take a screenshot.
  driver.findElement(By.id("hplogo"));

  // Google New York
  WebElement mobileSearchBox = driver.findElement(By.id("lst-ib"));
  mobileSearchBox.sendKeys("New York");
  WebElement searchBox;
  try {
    searchBox = driver.findElement(By.id("tsbb"));
  } catch (NoSuchElementException e) {
    searchBox = driver.findElement(By.name("btnG"));
  }
  searchBox.click();

  takeScreenshot();
  driver.navigate().refresh();
  takeScreenshot();

  // Quit the WebDriver instance on completion of the test.
  driver.quit();
  driver = null;
}
 
Example 49
Project: devtools-driver   File: RemoteWebElement.java   Source Code and License 5 votes vote down vote up
public RemoteWebElement findElementByCSSSelector(String selector) {
  JsonObject response = inspector.sendCommand(DOM.querySelector(nodeId.getId(), selector));
  // TODO freynaud
  NodeId id = new NodeId(response.getInt("nodeId"));
  if (!id.exist()) {
    throw new NoSuchElementException("no element matching " + selector);
  }
  RemoteWebElement res = new RemoteWebElement(id, inspector);
  return res;
}
 
Example 50
Project: devtools-driver   File: RemoteWebElement.java   Source Code and License 5 votes vote down vote up
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();
  }
}
 
Example 51
Project: devtools-driver   File: FindElementHandler.java   Source Code and License 5 votes vote down vote up
@Override
public Response handle() throws Exception {
  waitForPageToLoad();

  int implicitWait = getConf("implicit_wait", 0);
  long deadline = System.currentTimeMillis() + implicitWait;
  RemoteWebElement rwe = null;
  do {
    try {
      rwe = findElement();
      break;
    } catch (NoSuchElementException e) {
      // Ignore and try again.
    }
  } while (System.currentTimeMillis() < deadline);

  if (rwe == null) {
    throw new NoSuchElementException(
        "No element found for " + getRequest().getPayload() + " after waiting for " + implicitWait
        + " ms.");
  } else {
    JSONObject res = new JSONObject();
    res.put("ELEMENT", rwe.getReference());
    Response resp = new Response();
    resp.setSessionId(getSession().getSessionId());
    resp.setStatus(0);
    resp.setValue(res);
    return resp;
  }
}
 
Example 52
Project: devtools-driver   File: SetFrameHandler.java   Source Code and License 5 votes vote down vote up
private RemoteWebElement getIframe(String id) throws Exception {
  RemoteWebElement currentDocument = getWebDriver().getDocument();

  String
      selector =
      "iframe[name='" + id + "'],iframe[id='" + id + "'],frame[name='" + id + "'],frame[id='" + id
      + "']";
  try {
    RemoteWebElement frame = currentDocument.findElementByCSSSelector(selector);
    return frame;
  } catch (NoSuchElementException e) {
    throw new NoSuchFrameException(e.getMessage(), e);
  }
}
 
Example 53
Project: devtools-driver   File: FindElementsHandler.java   Source Code and License 5 votes vote down vote up
@Override
public Response handle() throws Exception {
  waitForPageToLoad();

  int implicitWait = getConf("implicit_wait", 0);
  long deadline = System.currentTimeMillis() + implicitWait;
  List<RemoteWebElement> elements = null;
  do {
    try {
      elements = findElements();
      if (elements.size() != 0) {
        break;
      }
    } catch (NoSuchElementException e) {
      // Ignore and try again.
    }
  } while (System.currentTimeMillis() < deadline);

  List<com.google.gson.JsonObject> list = new ArrayList<>();
  for (RemoteWebElement el : elements) {
    com.google.gson.JsonObject jsonObject = new com.google.gson.JsonObject();
    jsonObject.addProperty("ELEMENT", el.getReference());
    list.add(jsonObject);
  }

  Response resp = new Response();
  resp.setSessionId(getSession().getSessionId());
  resp.setStatus(0);
  resp.setValue(list);
  return resp;
}
 
Example 54
Project: chr-krenn-fhj-ws2017-sd17-pse   File: PageObject.java   Source Code and License 5 votes vote down vote up
boolean isElementPresent(By by) {
	try {
		getDriver().findElement(by);
		return true;
	} catch (NoSuchElementException e) {
		return false;
	}
}
 
Example 55
Project: tdd-pingpong   File: PageObject.java   Source Code and License 5 votes vote down vote up
public final boolean isCurrentPage() {
  try {
    waiting().until(titleContains(title));
    waiting().until(urlContains(urlTail));
    return true;
  } catch (NoSuchElementException e) {
    return false;
  }
}
 
Example 56
Project: tdd-pingpong   File: PageObject.java   Source Code and License 5 votes vote down vote up
protected final boolean existsById(String id) {
  try {
    findById(id);
    return true;
  } catch (NoSuchElementException e) {
    return false;
  }
}
 
Example 57
Project: tdd-pingpong   File: PageObject.java   Source Code and License 5 votes vote down vote up
protected boolean contains(WebElement element, String content) {
  try {
    waiting().until(textToBePresentInElement(element, content));
    return true;
  } catch (NoSuchElementException e) {
    return false;
  }
}
 
Example 58
Project: moviediary   File: UiSeriesPageTest.java   Source Code and License 5 votes vote down vote up
private void searchForSeries() {
    driver.findElementById("series-search").sendKeys("black mirror");
    driver.findElementByXPath("//label[@id='series-search-button']/i").click();
    await().ignoreExceptionsInstanceOf(NoSuchElementException.class).atMost(5, SECONDS)
            .until(() -> driver.findElementByCssSelector("span.truncate.series-search-title").isDisplayed());
    assertEquals("Black Mirror",
            driver.findElementByCssSelector("span.truncate.series-search-title").getText());
}
 
Example 59
Project: moviediary   File: UiMoviesPageTest.java   Source Code and License 5 votes vote down vote up
private void searchForMovie() {
    driver.findElementById("search").sendKeys("ghost in the shell");
    driver.findElementByXPath("//label[@id='search-button']/i").click();
    await().ignoreExceptionsInstanceOf(NoSuchElementException.class).atMost(5, SECONDS)
            .until(() -> driver.findElementByCssSelector("div.card-content.truncate").isDisplayed());
    assertTrue(driver.findElementByCssSelector("div.card-content.truncate")
            .getText().contains("Ghost in the Shell"));
}
 
Example 60
Project: mpay24-java   File: AbstractSeleniumTestcase.java   Source Code and License 5 votes vote down vote up
protected void assertNotExistent(RemoteWebDriver driver, By by) {
	try {
		driver.findElement(by);
		fail("Element with name '" + by + "' found");
	} catch (NoSuchElementException e) {
		; // That is what we expect
	}
}