Java Code Examples for org.openqa.selenium.WebDriver#findElement()
The following examples show how to use
org.openqa.selenium.WebDriver#findElement() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TypingTest.java From htmlunit with Apache License 2.0 | 6 votes |
/** * A test. */ @Test public void allPrintableKeys() { final WebDriver driver = getWebDriver("/javascriptPage.html"); final WebElement result = driver.findElement(By.id("result")); final WebElement element = driver.findElement(By.id("keyReporter")); final String allPrintable = "!\"#$%&'()*+,-./0123456789:;<=>?@ ABCDEFGHIJKLMNO" + "PQRSTUVWXYZ [\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; element.sendKeys(allPrintable); assertThat(element.getAttribute("value"), is(allPrintable)); assertThat(result.getText().trim(), containsString(" up: 16")); }
Example 2
Source File: NewUserRegisterPage.java From product-iots with Apache License 2.0 | 6 votes |
public NewUserRegisterPage(WebDriver driver) throws IOException { this.driver = driver; UIElementMapper uiElementMapper = UIElementMapper.getInstance(); // Check that we're on the right page. WebDriverWait webDriverWait = new WebDriverWait(driver, UIUtils.webDriverTimeOut); if (!webDriverWait.until(ExpectedConditions.titleContains(uiElementMapper.getElement("cdmf.register.page")))) { throw new IllegalStateException("This is not the Register page"); } firstNameField = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.input.firstname.xpath"))); lastNameField = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.input.lastname.xpath"))); emailField = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.input.email.xpath"))); userNameField = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.input.username.xpath"))); passwordField = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.input.password.xpath"))); passwordConfirmationField = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.input.confirmpassword.xpath"))); registerButton = driver.findElement(By.xpath( uiElementMapper.getElement("iot.user.add.register.button.xpath"))); }
Example 3
Source File: HTMLTextAreaElementTest.java From htmlunit with Apache License 2.0 | 6 votes |
/** * @throws Exception if the test fails */ @Test @Alerts("foo") public void onChange() throws Exception { final String html = "<html>\n" + "<head><title>foo</title></head>\n" + "<body>\n" + " <p>hello world</p>\n" + " <form name='form1'>\n" + " <textarea name='textarea1' onchange='alert(this.value)'></textarea>\n" + " <input name='myButton' type='button' onclick='document.form1.textarea1.value=\"from button\"'>\n" + " </form>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement textarea = driver.findElement(By.name("textarea1")); textarea.sendKeys("foo"); driver.findElement(By.name("myButton")).click(); verifyAlerts(driver, getExpectedAlerts()); }
Example 4
Source File: AugmenterTest.java From selenium with Apache License 2.0 | 6 votes |
@Test public void shouldAllowReflexiveCalls() { Capabilities caps = new ImmutableCapabilities("find by magic", true); StubExecutor executor = new StubExecutor(caps); final WebElement element = mock(WebElement.class); executor.expect( FIND_ELEMENT, ImmutableMap.of("using", "magic", "value", "cheese"), element); WebDriver driver = new RemoteWebDriver(executor, caps); WebDriver returned = getAugmenter() .addDriverAugmentation( "find by magic", FindByMagic.class, (c, exe) -> magicWord -> element) .augment(driver); // No exception is a Good Thing WebElement seen = returned.findElement(new ByMagic("cheese")); assertThat(seen).isSameAs(element); }
Example 5
Source File: KeyboardEventTest.java From htmlunit with Apache License 2.0 | 6 votes |
/** * @throws Exception if the test fails */ @Test @Alerts("32, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, ") @BuggyWebDriver(FF68 = "0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, ", FF60 = "0, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, ") public void keyCodes_keyup() throws Exception { final String html = "<html><head>\n" + "<script>\n" + "function handleKey(e) {\n" + " document.getElementById('log').value += e.keyCode + ', ';\n" + "}\n" + "</script>\n" + "</head>\n" + "<body>\n" + " <input id='t' onkeyup='handleKey(event)'/>\n" + " <textarea id='log' rows=40 cols=80></textarea>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement field = driver.findElement(By.id("t")); field.sendKeys(" 0123456789"); final String log = driver.findElement(By.id("log")).getAttribute("value"); assertEquals(getExpectedAlerts()[0], log); }
Example 6
Source File: ExpectedConditions.java From selenium with Apache License 2.0 | 6 votes |
/** * An expectation for checking child WebElement as a part of parent element to be visible * * @param parent used to check parent element. For example table with locator * By.id("fish") * @param childLocator used to find the ultimate child element. * @return visible nested element */ public static ExpectedCondition<List<WebElement>> visibilityOfNestedElementsLocatedBy( final By parent, final By childLocator) { return new ExpectedCondition<List<WebElement>>() { @Override public List<WebElement> apply(WebDriver driver) { WebElement current = driver.findElement(parent); List<WebElement> allChildren = current.findElements(childLocator); // The original code only checked the first element. Fair enough. if (!allChildren.isEmpty() && allChildren.get(0).isDisplayed()) { return allChildren; } return null; } @Override public String toString() { return String.format("visibility of elements located by %s -> %s", parent, childLocator); } }; }
Example 7
Source File: HTMLLabelElementTest.java From htmlunit with Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test public void clickByJSAfterNestedByJS() throws Exception { final String html = "<html>\n" + " <head>\n" + " <script>\n" + " function doTest() {\n" + " document.getElementById('label1').appendChild(document.getElementById('checkbox1'));\n" + " }\n" + " function delegateClick() {\n" + " try {\n" + " document.getElementById('label1').click();\n" + " } catch (e) {}\n" + " }\n" + " </script>\n" + " </head>\n" + " <body onload='doTest()'>\n" + " <label id='label1'>My Label</label>\n" + " <input type='checkbox' id='checkbox1'><br>\n" + " <input type=button id='button1' value='Test' onclick='delegateClick()'>\n" + " </body>\n" + "</html>"; final WebDriver driver = loadPage2(html); final WebElement checkbox = driver.findElement(By.id("checkbox1")); assertFalse(checkbox.isSelected()); driver.findElement(By.id("button1")).click(); assertTrue(checkbox.isSelected()); }
Example 8
Source File: Sarissa0993Test.java From htmlunit with Apache License 2.0 | 5 votes |
/** * @param expectedResult empty for successful test or in the form of "+++F+++" * for failing tests (see the results in a real browser) */ private static void verify(final WebDriver driver, final String testName, final String expectedResult) { final WebElement div = driver.findElement(By.xpath("//div[@class='placeholder' and a[@name='#" + testName + "']]")); String text = div.getText(); text = text.substring(0, text.indexOf(String.valueOf(expectedResult.length()))).trim(); assertEquals(testName + " Results\n" + expectedResult, text); }
Example 9
Source File: HtmlButton2Test.java From htmlunit with Apache License 2.0 | 5 votes |
/** * According to the HTML spec, the default type for a button is "submit". * IE is different than the HTML spec and has a default type of "button". * @throws Exception if the test fails */ @Test @Alerts({"submit", "1", "button-pushme", "Second"}) public void defaultButtonType_StandardsCompliantBrowser() throws Exception { final String firstContent = "<html><head><title>First</title></head><body>\n" + "<form id='form1' action='" + URL_SECOND + "' method='post'>\n" + " <button name='button' id='button' value='pushme'>PushMe</button>\n" + "</form></body></html>"; final String secondContent = "<html><head><title>Second</title></head><body'></body></html>"; getMockWebConnection().setResponse(URL_SECOND, secondContent); final WebDriver driver = loadPage2(firstContent); final WebElement button = driver.findElement(By.id("button")); assertEquals(getExpectedAlerts()[0], button.getAttribute("type")); button.click(); final List<NameValuePair> params = getMockWebConnection().getLastParameters(); assertEquals(getExpectedAlerts()[1], "" + params.size()); if (params.size() > 0) { assertEquals(getExpectedAlerts()[2], params.get(0).getName() + "-" + params.get(0).getValue()); } assertTitle(driver, getExpectedAlerts()[3]); }
Example 10
Source File: HtmlFileInputTest.java From htmlunit with Apache License 2.0 | 5 votes |
/** * Verifies that a asText() returns an empty string. * @throws Exception if the test fails */ @Test public void asText() throws Exception { final String htmlContent = "<html><head><title>foo</title></head><body>\n" + "<form id='form1'>\n" + " <input type='file' name='foo' id='foo' value='bla'>\n" + "</form></body></html>"; final WebDriver driver = loadPage2(htmlContent); final WebElement input = driver.findElement(By.id("foo")); assertEquals("", input.getText()); }
Example 11
Source File: HtmlOption2Test.java From htmlunit with Apache License 2.0 | 5 votes |
/** * @throws Exception if an error occurs */ @Test public void isSelectedJavaScript() throws Exception { final String html = "<html><head>\n" + "<script>\n" + " function test() {\n" + " var s = document.getElementsByTagName('select').item(0);\n" + " var options = s.options;\n" + " for (var i = 0; i < options.length; i++) {\n" + " options[i].selected = true;\n" + " }\n" + " }\n" + "</script>\n" + "</head><body onload='test()'>\n" + " <select multiple><option value='a'>a</option><option value='b'>b</option></select>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement select = driver.findElement(By.tagName("select")); final List<WebElement> options = select.findElements(By.tagName("option")); for (final WebElement option : options) { assertTrue(option.isSelected()); } }
Example 12
Source File: HtmlNumberInputTest.java From htmlunit with Apache License 2.0 | 5 votes |
/** * @throws Exception if the test fails */ @Test public void typeWhileDisabled() throws Exception { final String html = "<html><body><input type='number' id='p' disabled='disabled'/></body></html>"; final WebDriver driver = loadPage2(html); final WebElement p = driver.findElement(By.id("p")); try { p.sendKeys("abc"); fail(); } catch (final InvalidElementStateException e) { // as expected } assertEquals("", p.getAttribute("value")); }
Example 13
Source File: Edition114_Custom_ExpectedConditions.java From appiumpro with Apache License 2.0 | 5 votes |
private ExpectedCondition<Boolean> ZoomUIPresent() { return new ExpectedCondition<Boolean>() { @Override public Boolean apply(WebDriver driver) { try { driver.findElement(LEAVE_BTN); return true; } catch (NoSuchElementException ign) { driver.findElement(CONTENT).click(); } return false; } }; }
Example 14
Source File: MouseActions.java From vividus with Apache License 2.0 | 5 votes |
@Override public ClickResult clickViaJavascript(WebElement element) { ClickResult clickResult = new ClickResult(); if (element != null) { WebDriver webDriver = getWebDriver(); WebElement page = webDriver.findElement(BODY_XPATH_LOCATOR); webDriverEventListeners.forEach(listener -> listener.beforeClickOn(element, webDriver)); javascriptActions.click(element); webDriverEventListeners.forEach(listener -> listener.afterClickOn(element, webDriver)); afterClick(clickResult, page, webDriver, Optional.empty()); } return clickResult; }
Example 15
Source File: HTMLInputElementTest.java From htmlunit with Apache License 2.0 | 4 votes |
/** * @throws Exception if the test fails */ @Test @Alerts({"false", "true", "false", "true", "false", "true"}) public void disabledAttribute() throws Exception { final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + "<html><head><title>foo</title><script>\n" + "function test() {\n" + " alert(document.form1.button1.disabled);\n" + " alert(document.form1.button2.disabled);\n" + " alert(document.form1.button3.disabled);\n" + " document.form1.button1.disabled = true;\n" + " document.form1.button2.disabled = false;\n" + " document.form1.button3.disabled = true;\n" + " alert(document.form1.button1.disabled);\n" + " alert(document.form1.button2.disabled);\n" + " alert(document.form1.button3.disabled);\n" + "}\n" + "</script></head><body>\n" + "<p>hello world</p>\n" + "<form name='form1'>\n" + " <input type='submit' name='button1' value='1'/>\n" + " <input type='submit' name='button2' value='2' disabled/>\n" + " <input type='submit' name='button3' value='3'/>\n" + "</form>\n" + "<a href='javascript:test()' id='clickme'>click me</a>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); final WebElement button1 = driver.findElement(By.name("button1")); final WebElement button2 = driver.findElement(By.name("button2")); final WebElement button3 = driver.findElement(By.name("button3")); assertTrue(button1.isEnabled()); assertFalse(button2.isEnabled()); assertTrue(button3.isEnabled()); driver.findElement(By.id("clickme")).click(); verifyAlerts(driver, getExpectedAlerts()); assertFalse(button1.isEnabled()); assertTrue(button2.isEnabled()); assertFalse(button3.isEnabled()); }
Example 16
Source File: SearchTabBar.java From find with MIT License | 4 votes |
public SearchTabBar(final WebDriver driver) { bar = driver.findElement(By.className("search-tabs-list")); this.driver = driver; }
Example 17
Source File: ProductReviewTests.java From SeleniumBestPracticesBook with Apache License 2.0 | 4 votes |
@Test public void testAddNewReview() throws Exception { WebDriver selenium = new FirefoxDriver(); selenium.get("http://awful-valentine.com/"); selenium.findElement(By.cssSelector(".special-item a[href*=\"our-love-is-special\"].more-info")) .click(); assertEquals("http://awful-valentine.com/our-love-is-special/", selenium.getCurrentUrl()); assertEquals("Our love is special!!", selenium.findElement(By.className("category-title")).getText()); selenium.findElement(By.id("author")).sendKeys("Dima"); selenium.findElement(By.id("email")).sendKeys("[email protected]"); selenium.findElement(By.id("url")).sendKeys("http://awful-valentine.com"); selenium.findElement(By.cssSelector("a[title='5']")).click(); selenium.findElement(By.id("comment")).clear(); selenium.findElement(By.id("comment")) .sendKeys("This is a comment for product " + System.getProperty("user.name")); selenium.findElement(By.id("submit")).click(); if (!selenium.getCurrentUrl().contains("#")) { System.out.println("Something went wrong with creation of the test"); System.exit(1); } String[] splitString = selenium.getCurrentUrl().split("#"); String reviewId = splitString[1]; WebElement review = selenium.findElement(By.id(reviewId)); WebElement metaInfo = review.findElement(By.className("comment-author-metainfo")); String name = metaInfo.findElement(By.className("url")).getText(); String comment = review.findElement(By.className("comment-content")).getText();// assertEquals("Dima", name); assertEquals("This is a comment for product " + System.getProperty("user.name"), comment); selenium.quit(); }
Example 18
Source File: DojoTestBase.java From htmlunit with Apache License 2.0 | 4 votes |
void test(final String module) throws Exception { try { final WebDriver webdriver = getWebDriver(); final String url = URL_FIRST + "util/doh/runner.html?testModule=" + module; webdriver.get(url); final long runTime = 60 * DEFAULT_WAIT_TIME; final long endTime = System.currentTimeMillis() + runTime; // wait a bit to let the tests start Thread.sleep(DEFAULT_WAIT_TIME); String status = getResultElementText(webdriver); while (!"Stopped".equals(status)) { Thread.sleep(DEFAULT_WAIT_TIME); if (System.currentTimeMillis() > endTime) { fail("Test runs too long (longer than " + runTime / 1000 + "s)"); } status = getResultElementText(webdriver); } Thread.sleep(100); // to make tests a bit more stable final WebElement output = webdriver.findElement(By.id("logBody")); final List<WebElement> lines = output.findElements(By.xpath(".//div")); final StringBuilder result = new StringBuilder(); for (WebElement webElement : lines) { final String text = webElement.getText(); if (StringUtils.isNotBlank(text)) { result.append(text); result.append("\n"); } } String expFileName = StringUtils.replace(module, ".", ""); expFileName = StringUtils.replace(expFileName, "_", ""); String expected = loadExpectation(expFileName); expected = StringUtils.replace(expected, "\r\n", "\n"); assertEquals(normalize(expected), normalize(result.toString())); // assertEquals(expected, result.toString()); } catch (final Exception e) { e.printStackTrace(); Throwable t = e; while ((t = t.getCause()) != null) { t.printStackTrace(); } throw e; } }
Example 19
Source File: LogIn.java From java-maven-selenium with MIT License | 4 votes |
@Step("Give an option to Log In") public void giveAnOptionToLogIn() { WebDriver webDriver = Driver.webDriver; WebElement login = webDriver.findElement(submitLogIn); assertTrue(login.isDisplayed()); }
Example 20
Source File: HTMLOptionElement2Test.java From htmlunit with Apache License 2.0 | 4 votes |
/** * @throws Exception if the test fails */ @Test @Alerts(DEFAULT = "opt-a; opt-b", CHROME = "opt-b") @BuggyWebDriver("opt-a; b;") @NotYetImplemented //TODO: Needs further investigation of clicking an option without clicking the select // See the first comment in http://code.google.com/p/selenium/issues/detail?id=2131#c1 // Additionally, FF and Chrome drivers look buggy as they don't allow to capture // what happens when running the test manually in the browser. public void click2() throws Exception { final String html = HtmlPageTest.STANDARDS_MODE_PREFIX_ + "<html><head><title>foo</title><script>\n" + " function log(x) {\n" + " document.getElementById('log_').value += x + '; ';\n" + " }\n" + " function init() {\n" + " s = document.getElementById('s');\n" + " s.addEventListener('click', handle, false);\n" + " }\n" + " function handle(event) {\n" + " log(s.options[s.selectedIndex].value);\n" + " }\n" + "</script></head>\n" + "<body onload='init()'>\n" + "<form>\n" + " <textarea id='log_' rows='4' cols='50'></textarea>\n" + " <select id='s'>\n" + " <option value='opt-a'>A</option>\n" + " <option id='opt-b' value='b'>B</option>\n" + " <option value='opt-c'>C</option>\n" + " </select>\n" + "</form>\n" + "</body></html>"; final WebDriver driver = loadPage2(html); driver.findElement(By.id("s")).click(); driver.findElement(By.id("opt-b")).click(); final List<String> alerts = new LinkedList<>(); final WebElement log = driver.findElement(By.id("log_")); alerts.add(log.getAttribute("value").trim()); assertEquals(getExpectedAlerts(), alerts); }