Java Code Examples for org.openqa.selenium.WebElement#getAttribute()

The following examples show how to use org.openqa.selenium.WebElement#getAttribute() . 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: TCKLiferayTestDriver.java    From portals-pluto with Apache License 2.0 6 votes vote down vote up
protected void click(WebElement wel) {

	   boolean sennaJS = true;
	   String url = null;

	   if (wel != null) {
          String tagName = wel.getTagName();

	      if ("a".equals(tagName)) {
             url = wel.getAttribute("href");
             sennaJS = !url.contains("v3headerportlettests") && !url.contains("v3portlethubtests");
          }
	   }

	   if (sennaJS) {
          wel.click();
       } else {
          driver.get(url);
	   }
   }
 
Example 2
Source File: LibraryCollectionFeaturesEditLineAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * Helper method to edit a field's value.
 *
 * <p>This method has performs the following functions:<ul>
 * <li>Verifies that the values of the original dialog fields match those of the line fields.</li>
 * <li>Types the string provided, if provided, into the provided element, thereby editing the value of
 * the field.</li>
 * <li>If value of the field is edited, then the new values are checked for correctness.</li>
 * </ul></p>
 *
 * @param element the element in the dialog we are editing
 * @param randomString the string to edit with
 * @param fieldValue the value of the original field
 */
protected void verifyDialogField(WebElement element, String randomString, String fieldValue) throws Exception {
    // get the original values of the input fields
    String inputFieldValue = element.getAttribute("value");

    // make sure the input fields in the dialog match the line fields
    assertEquals("Value of input field in dialog does not match that of the line field's value.", fieldValue,
            inputFieldValue);

    if (StringUtils.isNotEmpty(randomString)) {
        // type the random string in the given input field
        element.sendKeys(randomString);

        // get the new values after typing
        String newInputFieldValue = element.getAttribute("value");

        // the first should have the original and the random string appended, while the second should be the same
        assertEquals(inputFieldValue + randomString, newInputFieldValue);
    }
}
 
Example 3
Source File: LibraryFieldsGroupLinkAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void testGroupLinkFieldNoLightbox() throws Exception {
    jGrowl("-- testGroupLinkFieldNoLightbox");
    WebElement exampleDiv = navigateToExample(DEMO_PAGE_ID4);
    assertTextPresent(DEMO_PAGE_HEADER4);

    WebElement field = findElement(By.cssSelector(UIF_LINK_CSS_SELECTOR), exampleDiv);

    verifyLinkIsInquiry(field);
    verifyKeyInInquiryHref(field, GROUP_INQUIRY_KEY_ID1);
    verifyLinkText(field, GROUP_LINKTEXT1);

    String dataOnClickScript = field.getAttribute("data-onclick");
    if ( StringUtils.contains(dataOnClickScript,"openLinkInDialog(jQuery(this), \"\");")) {
        fail("Lightbox not suppressed for Inquiry.");
    }

    waitAndClickByLinkText(field.getText());
    waitAndClickButtonByText("Back", "Unable to find Back button");
}
 
Example 4
Source File: StreamResourceIT.java    From flow with Apache License 2.0 6 votes vote down vote up
private void assertDownloadedContent(String downloadId, String filename)
        throws IOException {
    WebElement link = findElement(By.id(downloadId));
    Assert.assertEquals(
            "Anchor element should have router-ignore " + "attribute", "",
            link.getAttribute("router-ignore"));
    String url = link.getAttribute("href");

    getDriver().manage().timeouts().setScriptTimeout(15, TimeUnit.SECONDS);

    try (InputStream stream = download(url)) {
        List<String> lines = IOUtils.readLines(stream,
                StandardCharsets.UTF_8);
        String text = lines.stream().collect(Collectors.joining());
        Assert.assertEquals("foo", text);
    }

    Assert.assertEquals(filename, FilenameUtils.getName(url));
}
 
Example 5
Source File: BasicSmokeIT.java    From glowroot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldCheckActiveTraceModalPages() throws Exception {
    App app = app();
    GlobalNavbar globalNavbar = globalNavbar();
    JvmSidebar jvmSidebar = new JvmSidebar(driver);

    app.open();
    globalNavbar.clickJvmLink();
    jvmSidebar.clickThreadDumpLink();

    WebElement viewTraceLink = Utils.getWithWait(driver, Utils.linkText("view trace"));
    String href = viewTraceLink.getAttribute("href");
    String traceId = new QueryStringDecoder(href).parameters().get("modal-trace-id").get(0);
    clickLink("view trace");
    clickAroundInTraceModal(traceId, true);
}
 
Example 6
Source File: WebDriverService.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getAttributeFromHtml(Session session, Identifier identifier, String attribute) {
    String result = null;
    try {
        AnswerItem answer = this.getSeleniumElement(session, identifier, true, false);
        if (answer.isCodeEquals(MessageEventEnum.ACTION_SUCCESS_WAIT_ELEMENT.getCode())) {
            WebElement webElement = (WebElement) answer.getItem();
            if (webElement != null) {
                result = webElement.getAttribute(attribute);
            }
        }
    } catch (WebDriverException exception) {
        LOG.warn(exception.toString());
    }
    return result;
}
 
Example 7
Source File: CheckboxNameSearch.java    From vividus with Apache License 2.0 6 votes vote down vote up
private List<WebElement> searchCheckboxByLabels(SearchContext searchContext, SearchParameters parameters,
        List<WebElement> labelElements)
{
    for (WebElement label : labelElements)
    {
        List<WebElement> checkboxes;
        String checkBoxId = label.getAttribute("for");
        if (checkBoxId != null)
        {
            checkboxes = findElements(searchContext,
                    getXPathLocator("input[@type='checkbox' and @id=%s]", checkBoxId), parameters);
        }
        else
        {
            checkboxes = label.findElements(getXPathLocator(PRECEDING_SIBLING_CHECKBOX_LOCATOR));
            if (checkboxes.isEmpty())
            {
                continue;
            }
        }
        return checkboxes.stream().map(e -> new Checkbox(e, label)).collect(Collectors.toList());
    }
    return List.of();
}
 
Example 8
Source File: LibraryFieldsInputAft.java    From rice with Educational Community License v2.0 6 votes vote down vote up
protected void testInputFieldAltControl() throws Exception {
    WebElement exampleDiv = navigateToExample("Demo-InputField-Example2");
    WebElement field = findElement(By.cssSelector("div[data-label='InputField 2']"), exampleDiv);

    String fieldId = field.getAttribute("id");
    String controlId = fieldId + UifConstants.IdSuffixes.CONTROL;

    assertIsVisible("#" + fieldId);
    assertIsVisible("label[for='" + controlId + "']");
    WebElement label = findElement(By.cssSelector("label[for='" + controlId + "']"), field);
    if (!label.getText().contains("InputField 2:")) {
        fail("Label text does not match");
    }

    assertIsVisible("#" + controlId);

    waitAndType(By.cssSelector("#" + controlId), "Test InputField");

    // validate that the value comes after the label
    findElement(By.cssSelector("label[data-label_for='" + fieldId + "'] + textarea[id='" + controlId + "']"),
            exampleDiv);
}
 
Example 9
Source File: EncapsulateOperation.java    From LuckyFrameClient with GNU Affero General Public License v3.0 5 votes vote down vote up
public static String getOperation(WebDriver wd, WebElement we, String operation, String value) {
    String result = "";
    // ��ȡ������
    switch (operation) {
        case "gettext":
            result = "��ȡ����ֵ�ǡ�" + we.getText() + "��";
            LogUtil.APP.info("getText��ȡ����text����...��text����ֵ:{}��",result);
            break; // ��ȡ���������
        case "gettagname":
            result = "��ȡ����ֵ�ǡ�" + we.getTagName() + "��";
            LogUtil.APP.info("getTagName��ȡ����tagname����...��tagname����ֵ:{}��",result);
            break;
        case "getattribute":
            result = "��ȡ����ֵ�ǡ�" + we.getAttribute(value) + "��";
            LogUtil.APP.info("getAttribute��ȡ����{}������...��{}����ֵ:{}��",value,value,result);
            break;
        case "getcssvalue":
            result = "��ȡ����ֵ�ǡ�" + we.getCssValue(value) + "��";
            LogUtil.APP.info("getCssValue��ȡ����{}������...��{}����ֵ:{}��",value,value,result);
            break;
        case "getcaptcha":
            result = "��ȡ����ֵ�ǡ�" + Ocr.getCAPTCHA(wd, we) + "��";
            LogUtil.APP.info("getcaptcha��ȡ��֤��...����֤��ֵ:{}��",result);
            break;
        default:
            break;
    }
    return result;
}
 
Example 10
Source File: ExpectedConditions.java    From selenium with Apache License 2.0 5 votes vote down vote up
private static Optional<String> getAttributeOrCssValue(WebElement element, String name) {
  String value = element.getAttribute(name);
  if (value == null || value.isEmpty()) {
    value = element.getCssValue(name);
  }

  if (value == null || value.isEmpty()) {
    return Optional.empty();
  }

  return Optional.of(value);
}
 
Example 11
Source File: CustomConditions.java    From opentest with MIT License 5 votes vote down vote up
/**
 * Returns an ExpectedCondition instance that waits until an element becomes
 * the active (in-focus) element.
 */
public static ExpectedCondition<Boolean> elementToHaveClass(final WebElement element, String className) {
    return new ExpectedCondition<Boolean>() {
        @Override
        public Boolean apply(WebDriver driver) {
            try {
                String classAttribute = element.getAttribute("class");

                boolean foundClass = false;

                for (String currentClass : classAttribute.split(" ")) {
                    if (currentClass.equals(className)) {
                        return true;
                    }
                }
                
                return false;
            } catch (Exception ex) {
                return false;
            }
        }

        @Override
        public String toString() {
            return "element to have class: " + className;
        }
    };
}
 
Example 12
Source File: ExpectSteps.java    From NoraUi with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @deprecated As of release 4.1, replaced by {@link com.github.noraui.selenium.NoraUiExpectedConditions#textToBeEqualsToExpectedValue(By, String)}
 *             Expects that the target element contains the given value as text.
 *             The inner text and 'value' attribute of the element are checked.
 * @param locator
 *            is the selenium locator
 * @param value
 *            is the expected value
 * @return true or false
 */
@Deprecated
public static ExpectedCondition<Boolean> textToBeEqualsToExpectedValue(final By locator, final String value) {
    return (@Nullable WebDriver driver) -> {
        try {
            final WebElement element = driver.findElement(locator);
            if (element != null && value != null) {
                return !((element.getAttribute(VALUE) == null || !value.equals(element.getAttribute(VALUE).trim())) && !value.equals(element.getText().replaceAll("\n", "")));
            }
        } catch (final Exception e) {
        }
        return false;
    };
}
 
Example 13
Source File: LabelBy.java    From hsac-fitnesse-fixtures with Apache License 2.0 5 votes vote down vote up
public static WebElement getLabelledElement(SearchContext context, WebElement label) {
    WebElement element = null;
    if (label != null) {
        String forAttr = label.getAttribute("for");
        if (forAttr == null || "".equals(forAttr)) {
            element = ConstantBy.nestedElementForValue().findElement(label);
        } else {
            element = BestMatchBy.findElement(By.id(forAttr), context);
        }
    }
    return element;
}
 
Example 14
Source File: EventTest.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
private void document_input(final String event) throws Exception {
    final String html = "<html>\n"
            + "<head>\n"
            + "<script>\n"
            + "  function test() {\n"
            + "    handle(document);\n"
            + "  }\n"
            + "  function handle(obj) {\n"
            + "    obj.addEventListener('" + event + "', handler, true);\n"
            + "  }\n"
            + "  function handler(e) {\n"
            + "    var src = e.srcElement;\n"
            + "    if (!src)\n"
            + "      src = e.target;\n"
            + "    log(e.type + ' ' + src.nodeName);\n"
            + "  }\n"
            + "  function log(x) {\n"
            + "    document.getElementById('log').value += x + '\\n';\n"
            + "  }\n"
            + "</script>\n"
            + "</head>\n"
            + "<body onload='test()'>\n"
            + "  <div id=\"div\">\n"
            + "    <input id=\"input1\" type=\"text\">\n"
            + "    <input id=\"input2\" type=\"text\">\n"
            + "  </div>\n"
            + "<textarea id='log' cols='80' rows='40'></textarea>\n"
            + "</body></html>";

    final WebDriver driver = loadPage2(html);
    final WebElement logElement = driver.findElement(By.id("log"));
    final String initialValue = logElement.getAttribute("value");
    driver.findElement(By.id("input1")).click();
    driver.findElement(By.id("input2")).click();
    final String addedValue = logElement.getAttribute("value").substring(initialValue.length());
    final String text = addedValue.trim().replaceAll("\r", "");
    assertEquals(String.join("\n", getExpectedAlerts()), text);
}
 
Example 15
Source File: AppPage.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Returns the id of the table
 *         (which is of type {@code class=table}) in the page.
 */
public String getDataTableId(int tableNum) {
    WebElement tableElement = browser.driver.findElements(By.className("table")).get(tableNum);
    return tableElement.getAttribute("id");
}
 
Example 16
Source File: InstructorFeedbackEditPage.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
public boolean isRubricColLeftMovable(int qnNumber, int colNumber) {
    String elemId = Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_MOVE_COL_LEFT + "-" + qnNumber + "-" + colNumber;
    WebElement moveColButton = browser.driver.findElement(By.id(elemId));

    return moveColButton.getAttribute("disabled") == null;
}
 
Example 17
Source File: AccountApplicationsPage.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public Map<String, AppEntry> getApplications() {
    Map<String, AppEntry> table = new HashMap<String, AppEntry>();
    for (WebElement r : driver.findElements(By.tagName("tr"))) {
        int count = 0;
        AppEntry currentEntry = null;

        for (WebElement col : r.findElements(By.tagName("td"))) {
            count++;
            switch (count) {
                case 1:
                    currentEntry = new AppEntry();
                    String client = col.getText();
                    WebElement link = null;
                    try {
                        link = col.findElement(By.tagName("a"));
                        String href = link.getAttribute("href");
                        currentEntry.setHref(href);
                    } catch (Exception e) {
                        //ignore
                    }
                    table.put(client, currentEntry);
                    break;
                case 2:
                    String rolesStr = col.getText();
                    String[] roles = rolesStr.split(",");
                    for (String role : roles) {
                        role = role.trim();
                        currentEntry.addAvailableRole(role);
                    }
                    break;
                case 3:
                    String clientScopesStr = col.getText();
                    if (clientScopesStr.isEmpty()) break;
                    String[] clientScopes = clientScopesStr.split(",");
                    for (String clientScope : clientScopes) {
                        clientScope = clientScope.trim();
                        currentEntry.addGrantedClientScope(clientScope);
                    }
                    break;
                case 4:
                    String additionalGrant = col.getText();
                    if (additionalGrant.isEmpty()) break;
                    String[] grants = additionalGrant.split(",");
                    for (String grant : grants) {
                        grant = grant.trim();
                        currentEntry.addAdditionalGrant(grant);
                    }
                    break;
            }
        }
    }
    table.remove("Application");
    return table;
}
 
Example 18
Source File: InstructorFeedbackEditPage.java    From teammates with GNU General Public License v2.0 4 votes vote down vote up
public String getGiverTypeForQuestion(int qnNumber) {
    WebElement giverDropdownForQuestion = browser.driver.findElement(By.id("givertype-" + qnNumber));
    return giverDropdownForQuestion.getAttribute("value");
}
 
Example 19
Source File: LocatingElementListHandlerTest.java    From selenium with Apache License 2.0 4 votes vote down vote up
public void getLinks() {
  for (WebElement element : links) {
    element.getAttribute("href");
  }
}
 
Example 20
Source File: LibraryFieldsImageAft.java    From rice with Educational Community License v2.0 3 votes vote down vote up
protected void testImageFieldAlternateText() throws Exception {
    WebElement exampleDiv = navigateToExample("Demo-ImageField-Example2");
    WebElement field = findElement(By.cssSelector("div[data-label='ImageField 1']"), exampleDiv);

    String fieldId = field.getAttribute("id");

    WebElement label = findElement(By.cssSelector("label[data-label_for='" + fieldId + "']"), field);

    String imgId = label.getAttribute("for");

    assertIsVisible("#" + imgId + "[src='/krad/images/pdf_ne.png']");
    assertIsVisible("#" + imgId + "[alt='pdf']");
}