下面列出了怎么用org.openqa.selenium.NoSuchElementException的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 複数セレクタで複数の要素を指定して非表示にするが、そのうちのいずれかは存在しない要素である。
*
* @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)))));
}
}
}
@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;
}
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);
}
}
}
/**
* 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()));
}
/**
* 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;
}
}
});
}
/**
* 存在しない要素を指定して撮影する。
*
* @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();
}
@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")));
}
private boolean isAIA() {
try {
registerAIAButton.getText();
cancelAIAButton.getText();
return true;
} catch (NoSuchElementException e) {
return false;
}
}
public String getAccessTokenString() {
try {
return accessTokenString.getText();
} catch (NoSuchElementException nsee) {
log.warn("No accessTokenString element found on the page");
}
return null;
}
@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);
}
/**
* driver -> ???
*/
@Test
public void findElement_driver_notFound() throws Exception {
expectedException.expect(NoSuchElementException.class);
DomSelector selector = new DomSelector(SelectorType.TAG_NAME, "none");
selector.findElement(driver);
}
public boolean isOtpLabelPresent() {
try {
return otpInputLabel.isDisplayed();
} catch (NoSuchElementException e) {
return false;
}
}
/**
* 単体セレクタで存在しない要素を指定して非表示にする。
*
* @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);
// エラーとならない
}
@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);
}
public boolean isPresent() {
try {
return alertRoot.isDisplayed();
}
catch (NoSuchElementException e) {
return false;
}
}
private int getCourseCount() {
try {
return activeCoursesTable.findElements(By.cssSelector("tbody tr")).size();
} catch (NoSuchElementException e) {
return 0;
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
/**
* @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;
}
}
});
}
/**
* 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;
}
/** 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..");
}
}
/**
* 判断页面内是否存在Element.
*/
public boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
/**
* @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);
}
@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
}
}
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) {
}
}
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
}
}
public boolean emailWasSent() {
try {
List<WebElement> confirmations = allByClassName("confirmation");
return !confirmations.isEmpty();
} catch (NoSuchElementException e) {
return true;
}
}
public boolean isOnPage() {
try {
getSubmittedCommentText();
return true;
} catch (NoSuchElementException ex) {
return false;
}
}
/**
* 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;
}
@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)));
}
/**
* 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;
}
}