类org.openqa.selenium.NoSuchElementException源码实例Demo

下面列出了怎么用org.openqa.selenium.NoSuchElementException的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hifive-pitalium   文件: HideMultiElementsTest.java
/**
 * 複数セレクタで複数の要素を指定して非表示にするが、そのうちのいずれかは存在しない要素である。
 * 
 * @ptl.expect エラーが発生せず、非表示に指定した要素が写っていないこと。
 */
@Test
public void multiTargets_notExist() throws Exception {
	openBasicColorPage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().addHiddenElementsById("not-exists")
			.addHiddenElementsById("colorColumn1").addHiddenElementsById("colorColumn2").build();
	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	}
	assertionView.assertView(arg);

	// Check
	// 特定の色のピクセルが存在しないこと
	BufferedImage image = loadTargetResults("s").get(0).getImage().get();
	int width = image.getWidth();
	int height = image.getHeight();
	for (int x = 0; x < width; x++) {
		for (int y = 0; y < height; y++) {
			Color actual = Color.valueOf(image.getRGB(x, y));
			assertThat(actual, is(not(anyOf(equalTo(Color.GREEN), equalTo(Color.BLUE)))));
		}
	}
}
 
源代码2 项目: keycloak   文件: SelectAuthenticatorPage.java
@Override
public boolean isCurrent() {
    // Check the title
    if (!DroneUtils.getCurrentDriver().getTitle().startsWith("Log in to ") && !DroneUtils.getCurrentDriver().getTitle().startsWith("Anmeldung bei ")) {
        return false;
    }

    // Check the authenticators-choice available
    try {
        driver.findElement(By.id("kc-select-credential-form"));
    } catch (NoSuchElementException nfe) {
        return false;
    }

    return true;
}
 
源代码3 项目: kurento-room   文件: RoomClientBrowserTest.java
public WebElement findElement(String label, Browser browser, String id) {
  try {
    return new WebDriverWait(browser.getWebDriver(), testTimeout, POLLING_LATENCY)
        .until(ExpectedConditions.presenceOfElementLocated(By.id(id)));
  } catch (TimeoutException e) {
    log.warn("Timeout when waiting for element {} to exist in browser {}", id, label);
    int originalTimeout = 60;
    try {
      originalTimeout = browser.getTimeout();
      log.debug("Original browser timeout (s): {}, set to 10", originalTimeout);
      browser.setTimeout(10);
      browser.changeTimeout(10);
      WebElement elem = browser.getWebDriver().findElement(By.id(id));
      log.info("Additional findElement call was able to locate {} in browser {}", id, label);
      return elem;
    } catch (NoSuchElementException e1) {
      log.debug("Additional findElement call couldn't locate {} in browser {} ({})", id, label,
          e1.getMessage());
      throw new NoSuchElementException("Element with id='" + id + "' not found after "
          + testTimeout + " seconds in browser " + label);
    } finally {
      browser.setTimeout(originalTimeout);
      browser.changeTimeout(originalTimeout);
    }
  }
}
 
源代码4 项目: hifive-pitalium   文件: ExcludeInFrameTest.java
/**
 * BODYを撮影する際にiframe内外のs存在しない要素を除外する。
 * 
 * @ptl.expect エラーが発生せず、除外領域が保存されていないこと。
 */
@Test
public void captureBody_excludeNotExistElementInsideAndOutsideFrame() throws Exception {
	openIFramePage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().moveTarget(true).scrollTarget(false)
			.addExcludeByClassName("not-exists").addExcludeByClassName("not-exists").inFrameByClassName("content")
			.build();
	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	}
	assertionView.assertView(arg);

	// Check
	TargetResult result = loadTargetResults("s").get(0);
	assertThat(result.getExcludes(), is(empty()));
}
 
源代码5 项目: webtester-core   文件: Select.java
/**
 * Returns the first selected option's value. If nothing is selected
 * <code>null</code> is returned.
 *
 * @return the value of the first selected option.
 * @since 0.9.0
 */
public String getFirstSelectedValue() {
    return executeAction(new PageObjectCallbackWithReturnValue<String>() {

        @Override
        public String execute(PageObject pageObject) {
            try {
                return getFirstSelectedOption().getAttribute("value");
            } catch (NoSuchElementException e) {
                logger.warn(logMessage(NOTHING_SELECTED_VALUE));
                return null;
            }
        }

    });
}
 
源代码6 项目: hifive-pitalium   文件: NoSuchElementTest.java
/**
 * 存在しない要素を指定して撮影する。
 * 
 * @ptl.expect AssertionErrorが発生すること。
 */
@Test
public void noSuchElement() throws Exception {
	openBasicTextPage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTargetById("notExists").build();

	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	} else {
		expectedException.expect(AssertionError.class);
		expectedException.expectMessage("Invalid selector found");
	}
	assertionView.assertView(arg);
	fail();
}
 
源代码7 项目: selenium   文件: AugmenterTest.java
@Test
public void proxyShouldNotAppearInStackTraces() {
  // This will force the class to be enhanced
  final Capabilities caps = new ImmutableCapabilities("magic.numbers", true);

  DetonatingDriver driver = new DetonatingDriver();
  driver.setCapabilities(caps);

  WebDriver returned = getAugmenter()
    .addDriverAugmentation(
      "magic.numbers",
      HasMagicNumbers.class,
      (c, exe) -> () -> 42)
    .augment(driver);

  assertThatExceptionOfType(NoSuchElementException.class)
    .isThrownBy(() -> returned.findElement(By.id("ignored")));
}
 
源代码8 项目: keycloak   文件: WebAuthnRegisterPage.java
private boolean isAIA() {
    try {
        registerAIAButton.getText();
        cancelAIAButton.getText();
        return true;
    } catch (NoSuchElementException e) {
        return false;
    }
}
 
源代码9 项目: keycloak   文件: AbstractShowTokensPage.java
public String getAccessTokenString() {
    try {
        return accessTokenString.getText();
    } catch (NoSuchElementException nsee) {
        log.warn("No accessTokenString element found on the page");
    }

    return null;
}
 
源代码10 项目: selenium   文件: AjaxElementLocatorTest.java
@Test
public void shouldAlwaysDoAtLeastOneAttemptAtFindingTheElement() throws Exception {
  Field f = Page.class.getDeclaredField("first");
  final WebDriver driver = mock(WebDriver.class);
  final By by = new ByIdOrName("first");

  when(driver.findElement(by)).thenThrow(new NoSuchElementException("bar"));

  ElementLocator locator = new MonkeyedAjaxElementLocator(clock, driver, f, 0);

  assertThatExceptionOfType(NoSuchElementException.class)
      .isThrownBy(locator::findElement);

  verify(driver, atLeast(2)).findElement(by);
}
 
源代码11 项目: hifive-pitalium   文件: DomSelectorTest.java
/**
 * driver -> ???
 */
@Test
public void findElement_driver_notFound() throws Exception {
	expectedException.expect(NoSuchElementException.class);

	DomSelector selector = new DomSelector(SelectorType.TAG_NAME, "none");
	selector.findElement(driver);
}
 
源代码12 项目: keycloak   文件: OneTimeCode.java
public boolean isOtpLabelPresent() {
    try {
        return otpInputLabel.isDisplayed();
    } catch (NoSuchElementException e) {
        return false;
    }
}
 
源代码13 项目: hifive-pitalium   文件: HideSingleElementTest.java
/**
 * 単体セレクタで存在しない要素を指定して非表示にする。
 * 
 * @ptl.expect エラーが発生しないこと。
 */
@Test
public void notExists() throws Exception {
	openBasicColorPage();

	ScreenshotArgument arg = ScreenshotArgument.builder("s").addNewTarget().addHiddenElementsById("not-exists")
			.build();
	if (BrowserType.SAFARI.equals(capabilities.getBrowserName())) {
		expectedException.expect(NoSuchElementException.class);
	}
	assertionView.assertView(arg);

	// エラーとならない
}
 
源代码14 项目: qaf   文件: ByAny.java
@Override
public WebElement findElement(SearchContext context) {
	List<WebElement> elements = findElements(context);
	if (elements.isEmpty()) {
		throw new NoSuchElementException("Cannot locate an element using " + toString());
	}
	return elements.get(0);
}
 
源代码15 项目: keycloak   文件: FeedbackMessage.java
public boolean isPresent() {
    try {
        return alertRoot.isDisplayed();
    }
    catch (NoSuchElementException e) {
        return false;
    }
}
 
源代码16 项目: teammates   文件: InstructorCoursesPage.java
private int getCourseCount() {
    try {
        return activeCoursesTable.findElements(By.cssSelector("tbody tr")).size();
    } catch (NoSuchElementException e) {
        return 0;
    }
}
 
源代码17 项目: user-registration-V2   文件: RegisterierungTest.java
private boolean isElementPresent(By by) {
	try {
		driver.findElement(by);
		return true;
	} catch (NoSuchElementException e) {
		return false;
	}
}
 
源代码18 项目: webtester-core   文件: PageObject.java
/**
 * @return whether or not the {@linkplain PageObject} exists and is
 * currently visible
 * @since 0.9.0
 */
public boolean isVisible() {
    return executeAction(new PageObjectCallbackWithReturnValue<Boolean>() {

        @Override
        public Boolean execute(PageObject pageObject) {
            try {
                return pageObject.getWebElement().isDisplayed();
            } catch (NoSuchElementException e) {
                return Boolean.FALSE;
            }
        }

    });
}
 
源代码19 项目: keycloak   文件: UIUtils.java
/**
 * Contains some browser-specific tweaks for getting an element text.
 *
 * @param element
 * @return
 */
public static String getTextFromElement(WebElement element) {
    String text = element.getText();
    if (getCurrentDriver() instanceof SafariDriver) {
        try {
            // Safari on macOS doesn't comply with WebDriver specs yet again - getText() retrieves hidden text by CSS.
            text = element.findElement(By.xpath("./span[not(contains(@class,'ng-hide'))]")).getText();
        }
        catch (NoSuchElementException e) {
            // no op
        }
        return text.trim(); // Safari on macOS sometimes for no obvious reason surrounds the text with spaces
    }
    return text;
}
 
源代码20 项目: carina   文件: AndroidUtils.java
/** Scroll Timeout check
 * @param startTime - Long initial time for timeout count down
 **/
public static void checkTimeout(long startTime){
    long elapsed = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis())-startTime;

    if (elapsed > SCROLL_TIMEOUT) {
        throw new NoSuchElementException("Scroll timeout has been reached..");
    }
}
 
源代码21 项目: base-framework   文件: Selenium2.java
/**
 * 判断页面内是否存在Element.
 */
public boolean isElementPresent(By by) {
	try {
		driver.findElement(by);
		return true;
	} catch (NoSuchElementException e) {
		return false;
	}
}
 
源代码22 项目: htmlunit   文件: HtmlPage3Test.java
/**
 * @throws Exception if an error occurs
 */
@Test
@Alerts(DEFAULT = "error",
        CHROME = "Something")
@NotYetImplemented({IE, FF, FF68, FF60})
public void shouldBeAbleToFindElementByXPathInXmlDocument() throws Exception {
    final String html = "<?xml version='1.0' encoding='UTF-8'?>\n"
        + "<html xmlns='http://www.w3.org/1999/xhtml'\n"
        + "      xmlns:svg='http://www.w3.org/2000/svg'\n"
        + "      xmlns:xlink='http://www.w3.org/1999/xlink'>\n"
        + "<body>\n"
        + "  <svg:svg id='chart_container' height='220' width='400'>\n"
        + "    <svg:text y='16' x='200' text-anchor='middle'>Something</svg:text>\n"
        + "  </svg:svg>\n"
        + "</body>\n"
        + "</html>\n";

    final WebDriver driver = loadPage2(html, URL_FIRST, "application/xhtml+xml", ISO_8859_1, null);
    String actual;
    try {
        final WebElement element = driver.findElement(By.xpath("//svg:svg//svg:text"));
        actual = element.getText();
    }
    catch (final NoSuchElementException e) {
        actual = "error";
    }
    assertEquals(getExpectedAlerts()[0], actual);
}
 
源代码23 项目: ambari-logsearch   文件: LogSearchUISteps.java
@Then("element does not exist with xpath: $xpath")
public void doNotFindByXPath(@Named("xpath") String xPath) {
  try {
    LOG.info("Check that element does not exist with xpath: {}", xPath);
    home.findElement(By.xpath(xPath));
    Assert.fail(String.format("Element is found. xPath: '%s'", xPath));
  } catch (NoSuchElementException e) {
    // success
  }
}
 
源代码24 项目: oxTrust   文件: AbstractPage.java
public void fluentWait(int seconds) {
	try {
		Wait<WebDriver> wait = new FluentWait<WebDriver>(webDriver).withTimeout(seconds, TimeUnit.SECONDS)
				.pollingEvery(5, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

		wait.until(new Function<WebDriver, WebElement>() {
			public WebElement apply(WebDriver driver) {
				return driver.findElement(locator);
			}
		});
	} catch (Exception e) {

	}
}
 
源代码25 项目: ambari-logsearch   文件: LogSearchUISteps.java
private void closeTourPopup() {
  LOG.info("Close Tour popup if needed.");
  try {
    home.findElement(By.cssSelector("div.modal-footer > button.btn.btn-default")).click();
  } catch (NoSuchElementException ex) {
    // do nothing - no popup
  }
}
 
源代码26 项目: mamute   文件: ForgotPasswordPage.java
public boolean emailWasSent() {
    try {
    	List<WebElement> confirmations = allByClassName("confirmation");
    	return !confirmations.isEmpty();
    } catch (NoSuchElementException e) {
        return true;
    }
}
 
源代码27 项目: demo-java   文件: GuineaPigPage.java
public boolean isOnPage() {
    try {
        getSubmittedCommentText();
        return true;
    } catch (NoSuchElementException ex) {
        return false;
    }
}
 
源代码28 项目: movieapp-dialog   文件: BaseUI.java
/**
 * isVisible - Checks whether the given locator matches a visible WebElement
 * @param locator The locator for the element
 * @return true if the element is found and visible
 */
public boolean isVisible(String locator) {
	boolean found = false;
       try{
           WebElement element = findElement(locator);
           if(element.isDisplayed()){
           	logger.info("INFO: Element " + locator + " found and is visible");
           	found = true;
           }
       }catch (NoSuchElementException err){
       	//Ignore
       }
       return found;
}
 
源代码29 项目: selenium   文件: PageFactoryTest.java
@Test
public void shouldNotThrowANoSuchElementExceptionWhenUsedWithAFluentWait() {
  driver = mock(WebDriver.class);
  when(driver.findElement(ArgumentMatchers.any())).thenThrow(new NoSuchElementException("because"));

  TickingClock clock = new TickingClock();
  Wait<WebDriver> wait = new WebDriverWait(driver, Duration.ofSeconds(1), Duration.ofMillis(1001), clock, clock);

  PublicPage page = new PublicPage();
  PageFactory.initElements(driver, page);
  WebElement element = page.q;

  assertThatExceptionOfType(TimeoutException.class)
      .isThrownBy(() -> wait.until(ExpectedConditions.visibilityOf(element)));
}
 
源代码30 项目: product-iots   文件: GraphHandler.java
/**
 * Check the graph path is visible or not.
 *
 * @param graph : web element of the graph
 * @return : True if the path is visible. False otherwise
 */
public boolean isPathAvailable(WebElement graph) {
    try {
        WebElement graphContainer = getGraph(graph, uiElementMapper.getElement("iot.stat.graph.class.name"));
        return graphContainer != null && graphContainer.findElement(By.tagName("path")).isDisplayed();
    } catch (NoSuchElementException e) {
        log.error(String.format("No element found. \n %s", e.getMessage()));
        return false;
    }
}
 
 类所在包
 类方法
 同包方法