org.openqa.selenium.WebElement Java Examples

The following examples show how to use org.openqa.selenium.WebElement. 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: GenericPageElement.java    From webtau with Apache License 2.0 7 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 #2
Source File: SeleniumJavaScriptClickLiveTest.java    From tutorials with 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 #3
Source File: ElementInteractor.java    From qaf with 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 #4
Source File: WebElementsStepsTests.java    From vividus with 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 #5
Source File: WebDriverWebController.java    From stevia with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #6
Source File: FieldActionsTests.java    From vividus with 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 #7
Source File: PtlWebDriver.java    From hifive-pitalium with 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 #8
Source File: SynchExplicitTest.java    From demo-java with 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 #9
Source File: HiddenHtmlElement.java    From ats-framework with 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 #10
Source File: TableServiceTest.java    From senbot with 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 #11
Source File: ChannelTester.java    From packagedrone with 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 File: RealHtmlElementLocator.java    From ats-framework with 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 #13
Source File: RetrieveAutomationDetails.java    From samples with 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 #14
Source File: JButtonHtmlTest.java    From marathonv5 with 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 #15
Source File: OpenIdConnectScopeAddPage.java    From oxTrust with MIT License 5 votes vote down vote up
public void save() {
	fluentWait(SMALL);
	WebElement buttonBar = webDriver.findElement(By.className("box-footer"));
	buttonBar.click();
	buttonBar.findElements(By.tagName("button")).get(0).click();
	fluentWait(SMALL);
}
 
Example #16
Source File: InstructorCourseEditPage.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
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 #17
Source File: BasicComponentIT.java    From flow with 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 #18
Source File: HiddenHtmlElement.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
/**
 * Simulate Space key
 */
@Override
@PublicAtsApi
public void pressSpaceKey() {

    new HiddenHtmlElementState(this).waitToBecomeExisting();

    WebElement element = HiddenHtmlElementLocator.findElement(this);
    new Actions(htmlUnitDriver).sendKeys(element, Keys.SPACE).perform();
}
 
Example #19
Source File: FluentWebElement.java    From webDriverExperiments with 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 #20
Source File: HomePage.java    From spring-session with 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 #21
Source File: DriverListner.java    From coteafs-selenium with 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 #22
Source File: General.java    From Cognizant-Intelligent-Test-Scripter with Apache License 2.0 5 votes vote down vote up
private Map<String, WebElement> getRelativeElement() {
    Map<String, WebElement> elementMap = new HashMap<>();
    if (Condition != null && !Condition.trim().isEmpty()) {
        WebElement element = AObject.findElement(Condition, Reference);
        if (element != null) {
            elementMap.put(Condition, element);
        }
    }
    return elementMap;
}
 
Example #23
Source File: WaitStepsTests.java    From vividus with 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 #24
Source File: InstructorStudentRecordsPage.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 #25
Source File: MVCTest.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Test
@RunAsClient
public void test() {
    webDriver.get(this.base.toExternalForm() + "app/hello?name=TomEE");
    WebElement h1 = webDriver.findElement(By.tagName("h1"));
    assertNotNull(h1);
    assertTrue(h1.getText().contains("Welcome TomEE !"));
}
 
Example #26
Source File: HiddenHtmlElement.java    From ats-framework with 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();
}
 
Example #27
Source File: DeselectedByTextsEvent.java    From webtester2-core with 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 #28
Source File: AdminSearchPage.java    From teammates with GNU General Public License v2.0 5 votes vote down vote up
public WebElement getStudentRow(StudentAttributes student) {
    String details = String.format("%s [%s] (%s)", student.course,
            student.section == null ? Const.DEFAULT_SECTION : student.section, student.team);
    List<WebElement> rows = browser.driver.findElements(By.cssSelector("#search-table-student tbody tr"));
    for (WebElement row : rows) {
        List<WebElement> columns = row.findElements(By.tagName("td"));
        if (columns.get(STUDENT_COL_DETAILS - 1).getAttribute("innerHTML").contains(details)
                && columns.get(STUDENT_COL_NAME - 1).getAttribute("innerHTML").contains(student.name)) {
            return row;
        }
    }
    return null;
}
 
Example #29
Source File: Select.java    From selenium with Apache License 2.0 5 votes vote down vote up
/**
 * Deselect all options that have a value matching the argument. That is, when given "foo" this
 * would deselect an option like:
 *
 * &lt;option value="foo"&gt;Bar&lt;/option&gt;
 *
 * @param value The value to match against
 * @throws NoSuchElementException If no matching option elements are found
 * @throws UnsupportedOperationException If the SELECT does not support multiple selections
 */
@Override
public void deselectByValue(String value) {
  if (!isMultiple()) {
    throw new UnsupportedOperationException(
      "You may only deselect options of a multi-select");
  }

  for (WebElement option : findOptionsByValue(value)) {
    setSelected(option, false);
  }
}
 
Example #30
Source File: DesignTacoControllerBrowserTest.java    From spring-in-action-5-samples with Apache License 2.0 5 votes vote down vote up
@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");
}