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

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

源代码1 项目: qaf   文件: ElementInteractor.java
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 "";
	}
}
 
@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");
}
 
源代码3 项目: stevia   文件: WebDriverWebController.java
/**
 * 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");
}
 
源代码4 项目: hifive-pitalium   文件: PtlWebDriver.java
/**
 * 要素の部分スクロール時、元画像からボーダーを切り取ります。
 *
 * @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);
}
 
源代码5 项目: webtau   文件: GenericPageElement.java
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;
}
 
源代码6 项目: samples   文件: RetrieveAutomationDetails.java
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;
}
 
源代码7 项目: demo-java   文件: SynchExplicitTest.java
@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);
    }
}
 
源代码8 项目: ats-framework   文件: HiddenHtmlElement.java
/**
 * 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();
}
 
源代码9 项目: ats-framework   文件: RealHtmlElementLocator.java
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));
        }

    }
 
@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);
}
 
源代码11 项目: packagedrone   文件: ChannelTester.java
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;
}
 
源代码12 项目: senbot   文件: TableServiceTest.java
@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);
}
 
源代码13 项目: vividus   文件: FieldActionsTests.java
@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);
}
 
源代码14 项目: vividus   文件: WebElementsStepsTests.java
@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);
}
 
源代码15 项目: webtester2-core   文件: DeselectedByTextsEvent.java
@Override
public PageFragmentEventBuilder<DeselectedByTextsEvent> setAfterData(WebElement webElement) {
    after = new EnhancedSelect(webElement).getAllSelectedOptions()
        .stream()
        .map(element -> StringUtils.defaultString(element.getText()))
        .collect(Collectors.toList());
    return this;
}
 
源代码16 项目: coteafs-selenium   文件: DriverListner.java
@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);
    }
}
 
源代码17 项目: htmlunit   文件: HtmlSubmitInputTest.java
/**
 * @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());
}
 
源代码18 项目: deltaspike   文件: InjectionDroneTest.java
@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));
}
 
源代码19 项目: htmlunit   文件: XMLSerializerTest.java
/**
 * @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"));
}
 
源代码20 项目: marathonv5   文件: JButtonHtmlTest.java
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());
}
 
源代码21 项目: teammates   文件: InstructorCourseEditPage.java
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;
}
 
源代码22 项目: rice   文件: JiraAwareAftBase.java
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;
}
 
源代码23 项目: supbot   文件: BubbleFunctions.java
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;
    }
 
源代码24 项目: htmlunit   文件: HtmlUrlInputTest.java
/**
 * @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"));
}
 
源代码25 项目: flow   文件: BasicComponentIT.java
@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());
}
 
源代码26 项目: webDriverExperiments   文件: FluentWebElement.java
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;
}
 
源代码27 项目: spring-session   文件: HomePage.java
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;
}
 
源代码28 项目: vividus   文件: WaitStepsTests.java
@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();
}
 
源代码29 项目: teammates   文件: InstructorStudentRecordsPage.java
/**
 * 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;
}
 
源代码30 项目: ats-framework   文件: HiddenHtmlElement.java
/**
 * 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();
}
 
 类所在包
 同包方法