Java Code Examples for org.openqa.selenium.WebElement

The following examples show how to use org.openqa.selenium.WebElement. These examples are extracted from open source projects. 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 Project: qaf   Source File: ElementInteractor.java    License: MIT License 6 votes vote down vote up
public Object fetchValue(String loc, Type type,
		Class<? extends QAFExtendedWebElement> eleClass) {
	try {
		WebElement ele = getElement(loc, eleClass);
		switch (type) {
			case optionbox :
				return ele.getAttribute("value");
			case checkbox :
				return ele.isSelected();
			case selectbox :
				return new SelectBox(loc).getSelectedLable();
			case multiselectbox :
				return new SelectBox(loc).getSelectedLables();
			default :
				return ele.getText();
		}
	} catch (Exception e) {
		logger.warn(e.getMessage());
		return "";
	}
}
 
Example 2
@Test
@Ignore("TODO: Need to get around authentication in this test")
public void testDesignATacoPage() throws Exception {
  browser.get("http://localhost:" + port + "/design");

  List<WebElement> ingredientGroups = browser.findElementsByClassName("ingredient-group");
  assertEquals(5, ingredientGroups.size());
  
  WebElement wrapGroup = ingredientGroups.get(0);
  List<WebElement> wraps = wrapGroup.findElements(By.tagName("div"));
  assertEquals(2, wraps.size());
  assertIngredient(wrapGroup, 0, "FLTO", "Flour Tortilla");
  assertIngredient(wrapGroup, 1, "COTO", "Corn Tortilla");
  
  WebElement proteinGroup = ingredientGroups.get(1);
  List<WebElement> proteins = proteinGroup.findElements(By.tagName("div"));
  assertEquals(2, proteins.size());
  assertIngredient(proteinGroup, 0, "GRBF", "Ground Beef");
  assertIngredient(proteinGroup, 1, "CARN", "Carnitas");
}
 
Example 3
/**
 * Gets the table header position.
 * 
 * @param locator
 *            the locator
 * @param headerName
 *            the header name
 * @return the table header position
 */
public String getTableHeaderPosition(String locator, String headerName) {
	List<WebElement> columnHeaders = null;

	WebElement element = waitForElement(locator);

	columnHeaders = element.findElements(By.cssSelector("th"));

	int position = 1;
	for (WebElement record : columnHeaders) {
		if (record.getText().equals(headerName)) {
			return String.valueOf(position);
		}
		position++;
	}

	throw new WebDriverException("Header name not Found");
}
 
Example 4
Source Project: hifive-pitalium   Source File: PtlWebDriver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 要素の部分スクロール時、元画像からボーダーを切り取ります。
 *
 * @param el 対象の要素
 * @param image 元画像
 * @param num 何スクロール目の画像化
 * @param size 全体のスクロール数
 * @return ボーダーを切り取ったBufferedImage
 */
protected BufferedImage trimTargetBorder(WebElement el, BufferedImage image, int num, int size,
		double currentScale) {
	LOG.trace("(trimTargetBorder) el: {}; image[w: {}, h: {}], num: {}, size: {}", el, image.getWidth(),
			image.getHeight(), num, size);

	WebElementBorderWidth targetBorder = ((PtlWebElement) el).getBorderWidth();

	int trimTop = 0;
	int trimBottom = 0;
	if (size > 1) {
		if (num <= 0) {
			trimBottom = (int) Math.round(targetBorder.getBottom() * currentScale);
		} else if (num >= size - 1) {
			trimTop = (int) Math.round(targetBorder.getTop() * currentScale);
		} else {
			trimBottom = (int) Math.round(targetBorder.getBottom() * currentScale);
			trimTop = (int) Math.round(targetBorder.getTop() * currentScale);
		}
	}

	LOG.trace("(trimTargetBorder) top: {}, bottom: {}", trimTop, trimBottom);
	return ImageUtils.trim(image, trimTop, 0, trimBottom, 0);
}
 
Example 5
Source Project: webtau   Source File: GenericPageElement.java    License: Apache License 2.0 6 votes vote down vote up
private List<String> extractValues() {
    List<WebElement> elements = path.find(driver);
    List<Map<String, ?>> elementsMeta = handleStaleElement(() -> additionalBrowserInteractions.extractElementsMeta(elements),
            Collections.emptyList());

    if (elementsMeta.isEmpty()) {
        return Collections.emptyList();
    }

    List<String> result = new ArrayList<>();

    for (int idx = 0; idx < elements.size(); idx++) {
        HtmlNode htmlNode = new HtmlNode(elementsMeta.get(idx));
        PageElement pageElementByIdx = get(idx + 1);

        result.add(handleStaleElement(() ->
                PageElementGetSetValueHandlers.getValue(
                        htmlNode,
                        pageElementByIdx), null));
    }

    return result;
}
 
Example 6
Source Project: samples   Source File: RetrieveAutomationDetails.java    License: MIT License 6 votes vote down vote up
private AndroidDriver<WebElement> executeSimpleAppTest() throws MalformedURLException {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability("sessionName", "Android App Test");
    capabilities.setCapability("sessionDescription", "Kobiton sample session");
    capabilities.setCapability("deviceOrientation", "portrait");
    capabilities.setCapability("captureScreenshots", true);
    capabilities.setCapability("app", "https://s3-ap-southeast-1.amazonaws.com/kobiton-devvn/apps-test/demo/com.dozuki.ifixit.apk");
    capabilities.setCapability("deviceName", "Galaxy J7");
    capabilities.setCapability("platformName", "Android");
    
    AndroidDriver<WebElement> driver = new AndroidDriver<>(getAutomationUrl(), capabilities);
    
    try {
        driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
        driver.findElementByXPath("//*[@resource-id='android:id/home']").click();
    } catch (Exception e) {
        driver.quit();
        throw e;
    }
    
    return driver;
}
 
Example 7
Source Project: demo-java   Source File: SynchExplicitTest.java    License: MIT License 6 votes vote down vote up
@Test
public void synchronizeExplicit() {
    driver.get("http://watir.com/examples/wait.html");
    WebDriverWait wait = new WebDriverWait(driver, 30);

    wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("add_foobar")));
    driver.findElement(By.id("add_foobar")).click();

    WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("foobar")));

    try {
        element.click();
        session.stop(true);
    } catch (ElementNotInteractableException e) {
        session.stop(false);
        Assert.assertTrue(e.getMessage(), false);
    }
}
 
Example 8
Source Project: ats-framework   Source File: HiddenHtmlElement.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Drag and drop an element on top of other element
 * @param targetElement the target element
 */
@Override
@PublicAtsApi
public void dragAndDropTo(
                           HtmlElement targetElement ) {

    new HiddenHtmlElementState(this).waitToBecomeExisting();

    WebElement source = HiddenHtmlElementLocator.findElement(this);
    WebElement target = HiddenHtmlElementLocator.findElement(targetElement);

    Actions actionBuilder = new Actions(htmlUnitDriver);
    Action dragAndDropAction = actionBuilder.clickAndHold(source)
                                            .moveToElement(target, 1, 1)
                                            .release(target)
                                            .build();
    dragAndDropAction.perform();

    // drops the source element in the middle of the target, which in some cases is not doing drop on the right place
    // new Actions( htmlUnitDriver ).dragAndDrop( source, target ).perform();
}
 
Example 9
Source Project: ats-framework   Source File: RealHtmlElementLocator.java    License: Apache License 2.0 6 votes vote down vote up
public static List<WebElement> findElements( UiElement uiElement, String xpathSuffix, boolean verbose ) {

        AbstractRealBrowserDriver browserDriver = (AbstractRealBrowserDriver) uiElement.getUiDriver();
        WebDriver webDriver = (WebDriver) browserDriver.getInternalObject(InternalObjectsEnum.WebDriver.name());
        HtmlNavigator.getInstance().navigateToFrame(webDriver, uiElement);

        String xpath = uiElement.getElementProperties()
                                .getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR);

        String css = uiElement.getElementProperty("_css");

        if (xpathSuffix != null) {
            xpath += xpathSuffix;
        }

        if (!StringUtils.isNullOrEmpty(css)) {
            return webDriver.findElements(By.cssSelector(css));
        } else {
            return webDriver.findElements(By.xpath(xpath));
        }

    }
 
Example 10
Source Project: tutorials   Source File: SeleniumJavaScriptClickLiveTest.java    License: MIT License 6 votes vote down vote up
@Test
public void whenSearchForSeleniumArticles_thenReturnNotEmptyResults() {
    driver.get("https://baeldung.com");
    String title = driver.getTitle();
    assertEquals("Baeldung | Java, Spring and Web Development tutorials", title);

    wait.until(ExpectedConditions.elementToBeClickable(By.className("nav--menu_item_anchor")));
    WebElement searchButton = driver.findElement(By.className("nav--menu_item_anchor"));
    clickElement(searchButton);

    wait.until(ExpectedConditions.elementToBeClickable(By.id("search")));
    WebElement searchInput = driver.findElement(By.id("search"));
    searchInput.sendKeys("Selenium");

    wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector(".btn-search")));
    WebElement seeSearchResultsButton = driver.findElement(By.cssSelector(".btn-search"));
    clickElement(seeSearchResultsButton);

    wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.className("post")));
    int seleniumPostsCount = driver.findElements(By.className("post"))
        .size();
    assertTrue(seleniumPostsCount > 0);
}
 
Example 11
Source Project: packagedrone   Source File: ChannelTester.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected Set<String> internalGetAspects ( final String className )
{
    final List<WebElement> elements = this.context.findElements ( By.className ( className ) );

    final Set<String> result = new HashSet<> ( elements.size () );

    for ( final WebElement ele : elements )
    {
        final String id = ele.getAttribute ( "id" );
        if ( id != null )
        {
            result.add ( id );
        }
    }

    return result;
}
 
Example 12
Source Project: senbot   Source File: TableServiceTest.java    License: MIT License 6 votes vote down vote up
@Test
public void testCompareTable_rowIncludeAndIgnore() throws Throwable {
    seleniumNavigationService.navigate_to_url(MockReferenceDatePopulator.TABLE_TEST_PAGE_URL);
    WebElement table = seleniumElementService.translateLocatorToWebElement("Table locator");

    List<List<String>> expectedRows = new ArrayList<List<String>>();
    final List<String> row3 = Arrays.asList(new String[]{"Table cell 5", "Table cell 6"});

    expectedRows = new ArrayList<List<String>>() {
        {
            add(row3);
        }
    };

    DataTable expectedContent = mock(DataTable.class);
    when(expectedContent.raw()).thenReturn(expectedRows);

    ExpectedTableDefinition expectedTableDefinition = new ExpectedTableDefinition(expectedContent);
    expectedTableDefinition.getIncludeOnlyRowsMatching().add(By.className("odd"));
    expectedTableDefinition.getIgnoreRowsMatching().add(By.id("row1"));

    seleniumTableService.compareTable(expectedTableDefinition, table);
}
 
Example 13
Source Project: vividus   Source File: FieldActionsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testSelectItemInDDLMultiSelectNotAdditable()
{
    WebElement selectedElement = mock(WebElement.class);
    when(selectedElement.isSelected()).thenReturn(true);
    when(selectedElement.getAttribute(INDEX)).thenReturn(Integer.toString(1));
    Select select = findDropDownListWithParameters(true);

    List<WebElement> options = List.of(webElement, selectedElement);
    when(select.getOptions()).thenReturn(options);
    when(webElementActions.getElementText(webElement)).thenReturn(TEXT);
    when(webElementActions.getElementText(selectedElement)).thenReturn("not" + TEXT);
    fieldActions.selectItemInDropDownList(select, TEXT, false);
    verify(webElementActions).getElementText(webElement);
    verify(waitActions).waitForPageLoad();
    verify(softAssert).assertTrue(ITEMS_WITH_THE_TEXT_TEXT_ARE_SELECTED_FROM_A_DROP_DOWN,
            true);
}
 
Example 14
Source Project: vividus   Source File: WebElementsStepsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testCheckPageContainsTextThrowsWebDriverException()
{
    By locator = LocatorUtil.getXPathLocatorByInnerText(TEXT);
    List<WebElement> webElementList = List.of(mockedWebElement);
    when(webUiContext.getSearchContext()).thenReturn(webDriver);
    when(webDriver.findElements(locator)).thenAnswer(new Answer<List<WebElement>>()
    {
        private int count;

        @Override
        public List<WebElement> answer(InvocationOnMock invocation)
        {
            count++;
            if (count == 1)
            {
                throw new WebDriverException();
            }

            return webElementList;
        }
    });
    webElementsSteps.ifTextExists(TEXT);
    verify(softAssert).assertTrue(THERE_IS_AN_ELEMENT_WITH_TEXT_TEXT_IN_THE_CONTEXT, true);
}
 
Example 15
Source Project: webtester2-core   Source File: DeselectedByTextsEvent.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PageFragmentEventBuilder<DeselectedByTextsEvent> setAfterData(WebElement webElement) {
    after = new EnhancedSelect(webElement).getAllSelectedOptions()
        .stream()
        .map(element -> StringUtils.defaultString(element.getText()))
        .collect(Collectors.toList());
    return this;
}
 
Example 16
Source Project: coteafs-selenium   Source File: DriverListner.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void afterChangeValueOf(final WebElement element, final WebDriver driver, final CharSequence[] keysToSend) {
    if (keysToSend != null) {
        final String message = "Text {} has been entered in element [{}]...";
        LOG.t(message, keysToSend, name);
    }
}
 
Example 17
Source Project: htmlunit   Source File: HtmlSubmitInputTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("2")
public void doubleSubmission() throws Exception {
    final String html = "<html>\n"
        + "<head>\n"
        + "  <script type='text/javascript'>\n"
        + "    function submitForm() {\n"
        + "      document.deliveryChannelForm.submitBtn.disabled = true;\n"
        + "      document.deliveryChannelForm.submit();\n"
        + "    }\n"
        + "  </script>\n"
        + "</head>\n"
        + "<body>\n"
        + "  <form action='test' name='deliveryChannelForm'>\n"
        + "    <input name='submitBtn' type='submit' value='Save' title='Save' onclick='submitForm();'>\n"
        + "  </form>\n"
        + "</body>\n"
        + "</html>";

    getMockWebConnection().setDefaultResponse("");
    final WebDriver webDriver = loadPage2(html);
    final WebElement input = webDriver.findElement(By.name("submitBtn"));
    input.click();

    assertEquals(Integer.parseInt(getExpectedAlerts()[0]), getMockWebConnection().getRequestCount());
}
 
Example 18
Source Project: deltaspike   Source File: InjectionDroneTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
public void testValidatorWithError() throws MalformedURLException
{
    driver.get(new URL(contextPath, "testValidatorConverter.xhtml").toString());
    WebElement convertedValue = driver.findElement(By.id("validator:stringValue"));
    convertedValue.sendKeys("Wrong Value");
    WebElement testConveterButton = driver.findElement(By.id("validator:testValidatorButton"));
    testConveterButton.click();
    Assert.assertTrue(ExpectedConditions.textToBePresentInElement(By.id("validator:errorMessage"),
            "Not a valid value").apply(driver));
}
 
Example 19
Source Project: htmlunit   Source File: XMLSerializerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
@Alerts("<a><!--32abc32--></a>")
public void comment() throws Exception {
    final String expectedString = getExpectedAlerts()[0];
    setExpectedAlerts();
    final String serializationText = "<a><!-- abc --></a>";
    final WebDriver driver = loadPageWithAlerts2(constructPageContent(serializationText));
    final WebElement textArea = driver.findElement(By.id("myTextArea"));
    assertEquals(expectedString, textArea.getAttribute("value"));
}
 
Example 20
Source Project: marathonv5   Source File: JButtonHtmlTest.java    License: Apache License 2.0 5 votes vote down vote up
public void getText() throws Throwable {
    driver = new JavaDriver();
    List<WebElement> buttons = driver.findElements(By.cssSelector("button"));
    AssertJUnit.assertEquals(3, buttons.size());
    AssertJUnit.assertEquals("<html><center><b><u>D</u>isable</b><br><font color=#ffffdd>middle button</font>",
            buttons.get(0).getText());
    AssertJUnit.assertEquals("middle button", buttons.get(1).getText());
    AssertJUnit.assertEquals("<html><center><b><u>E</u>nable</b><br><font color=#ffffdd>middle button</font>",
            buttons.get(2).getText());
    WebElement buttonMiddle = driver.findElement(By.cssSelector("button[text^='middle']"));
    AssertJUnit.assertEquals("middle button", buttonMiddle.getText());
}
 
Example 21
public boolean isInstructorListSortedByName() {
    boolean isSorted = true;
    List<String> instructorNames = new ArrayList<>();
    List<WebElement> elements = browser.driver.findElements(By.xpath("//*[starts-with(@id, 'instructorname')]"));
    for (int i = 1; i < elements.size(); i++) {
        instructorNames.add(browser.driver.findElement(By.id("instructorname" + i)).getAttribute("value"));
    }
    for (int i = 1; i < instructorNames.size(); i++) {
        if (instructorNames.get(i - 1).compareTo(instructorNames.get(i)) > 0) {
            isSorted = false;
        }
    }
    return isSorted;
}
 
Example 22
Source Project: rice   Source File: JiraAwareAftBase.java    License: Educational Community License v2.0 5 votes vote down vote up
private WebElement type(By by, String text) {
    WebElement element = findElement(by);
    String name = element.getAttribute("name");
    WebDriverUtils.jGrowl(getDriver(), "Type", false, "Type into " + name + " the text: " + text);
    WebDriverUtils.highlightElement(getDriver(), element);
    element.sendKeys(text);
    return element;
}
 
Example 23
Source Project: supbot   Source File: BubbleFunctions.java    License: MIT License 5 votes vote down vote up
public static String getAuthorNameFromBubble(WebElement bubble, List<WebElement> bubbles){

        for(int i = bubbles.indexOf(bubble); i>=0; i--){

            if(doesHaveAuthorName(bubbles.get(i))) {
                return bubbles.get(i).findElement(By.xpath(XPaths.bubbleToAuthorName)).getText();
            }
        }

        return null;
    }
 
Example 24
Source Project: htmlunit   Source File: HtmlUrlInputTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @throws Exception if the test fails
 */
@Test
public void typing() throws Exception {
    final String htmlContent
        = "<html><head><title>foo</title></head><body>\n"
        + "<form id='form1'>\n"
        + "  <input type='url' id='foo'>\n"
        + "</form></body></html>";

    final WebDriver driver = loadPage2(htmlContent);

    final WebElement input = driver.findElement(By.id("foo"));
    input.sendKeys("hello");
    assertEquals("hello", input.getAttribute("value"));
}
 
Example 25
Source Project: flow   Source File: BasicComponentIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void tagsInText() {
    open();
    WebElement root = findElement(By.id("root"));

    // Selenium does not support text nodes...
    Assert.assertEquals(
            BasicComponentView.TEXT + "\n" + BasicComponentView.DIV_TEXT
                    + "\n" + BasicComponentView.BUTTON_TEXT,
            root.getText());
}
 
Example 26
Source Project: webDriverExperiments   Source File: FluentWebElement.java    License: MIT License 5 votes vote down vote up
public List<FluentWebElement> findElements(By by) {
    List<WebElement> webElements = webElement.findElements(by);
    List<FluentWebElement> fWebElements = new ArrayList<FluentWebElement>();

    for(WebElement aWebElement : webElements){
        fWebElements.add(new FluentWebElement(aWebElement));
    }
    return fWebElements;
}
 
Example 27
Source Project: spring-session   Source File: HomePage.java    License: Apache License 2.0 5 votes vote down vote up
public List<Attribute> attributes() {
	List<Attribute> rows = new ArrayList<>();
	for (WebElement tr : this.trs) {
		rows.add(new Attribute(tr));
	}
	this.attributes.addAll(rows);
	return this.attributes;
}
 
Example 28
Source Project: vividus   Source File: WaitStepsTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void testWaitTillElementsAreVisible()
{
    when(webUiContext.getSearchContext()).thenReturn(webElement);
    SearchAttributes attributes = new SearchAttributes(ActionAttributeType.ELEMENT_NAME, NAME);
    WaitResult<WebElement> waitResult = mock(WaitResult.class);
    IExpectedSearchContextCondition<WebElement> condition = mock(IExpectedSearchContextCondition.class);
    when(expectedSearchActionsConditions.visibilityOfElement(attributes)).thenReturn(condition);
    when(waitActions.wait(webElement, condition)).thenReturn(waitResult);
    waitSteps.waitTillElementsAreVisible(NAME);
    verify(waitResult).isWaitPassed();
}
 
Example 29
/**
 * Checks if the bodies of all the record panels are collapsed or expanded.
 * @param isVisible true to check for expanded, false to check for collapsed.
 * @return true if all record panel bodies are equals to the visibility being checked.
 */
private boolean areAllRecordPanelBodiesVisibilityEquals(boolean isVisible) {
    for (WebElement e : getStudentFeedbackPanels()) {
        if (e.isDisplayed() != isVisible) {
            return false;
        }
    }

    return true;
}
 
Example 30
Source Project: ats-framework   Source File: HiddenHtmlElement.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Set the content of the element
 * @param content the new content
 */
@PublicAtsApi
public void setTextContent(
                            String content ) {

    new HiddenHtmlElementState(this).waitToBecomeExisting();

    WebElement element = HiddenHtmlElementLocator.findElement(this);
    new Actions(htmlUnitDriver).sendKeys(element, content).perform();
}