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

The following are Jave code examples for showing how to use getAttribute() of the org.openqa.selenium.WebElement class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: kheera   File: PageObject.java   View Source Code Vote up 7 votes
/**
 * 1. map elements of interest to their name
 * 2. reload elements from the page every time `map` is called  
 * 
 * E.g., Say ELEMENT_LOCATORS=id 
 * 			and <input id="username" type="text"></input>
 * 			then nameElementMap will contain "username" => WebElement
 */
@Override
protected void map(AbstractPage p) {
	getBys();
	List<WebElement> elements = new ArrayList<WebElement>();
	for (By by : bys) {
		elements.addAll(driver.findElements(by));
	}
	PageFactory.initElements(driver, this);
	String[] tokens = locators.split(",");
	for(WebElement w: elements) {
		for (String s : tokens) {
			try{
				String attr = w.getAttribute(s);//throws StaleElementReferenceException
				if (attr != null) {
					nameElementMap.put(attr, w);
				}
			}catch(StaleElementReferenceException se){
				//ignoring elements which have become stale because
				//a stale object shouldn't have to be referenced 
				//by an automation script
			}
		}
	}
}
 
Example 2
Project: opentest   File: AssertElementReadOnly.java   View Source Code Vote up 6 votes
@Override
public void run() {

    super.run();

    By locator = this.readLocatorArgument("locator");

    this.waitForAsyncCallsToFinish();

    WebElement element = this.getElement(locator);
    String readonly = element.getAttribute("readonly");
    if (readonly == null) {
        throw new RuntimeException(String.format(
                "Assertion failed: the \"readonly\" attribute was not set on element %s",
                locator));
    }
}
 
Example 3
Project: opentest   File: AssertElementNotReadOnly.java   View Source Code Vote up 6 votes
@Override
public void run() {

    super.run();

    By locator = this.readLocatorArgument("locator");

    this.waitForAsyncCallsToFinish();

    WebElement element = this.getElement(locator);
    String readonly = element.getAttribute("readonly");
    if (readonly != null) {
        throw new RuntimeException(String.format(
                "Assertion failed: the \"readonly\" attribute was set on element %s",
                locator));
    }
}
 
Example 4
Project: marathonv5   File: JTableColumnSelectionTest.java   View Source Code Vote up 6 votes
public void columnSelection() throws Throwable {
    driver = new JavaDriver();
    List<WebElement> checkboxes = driver.findElements(By.cssSelector("check-box"));

    // Setting Column Selection
    checkboxes.get(1).click();
    List<WebElement> radiobuttons = driver.findElements(By.cssSelector("radio-button"));

    // Setting Single Selection
    radiobuttons.get(1).click();

    WebElement table = driver.findElement(By.cssSelector("table"));
    int columnCount = new Integer(table.getAttribute("columnCount"));
    AssertJUnit.assertEquals(5, columnCount);
    for (int colNum = 0; colNum < columnCount; colNum++) {
        assertClickOnColumn(table, colNum);
    }

    assertShiftClickSingleSelection(table);
}
 
Example 5
Project: marathonv5   File: JTableColumnSelectionTest.java   View Source Code Vote up 6 votes
public void colSelectionSingleInterval() throws Throwable {
    driver = new JavaDriver();
    List<WebElement> checkboxes = driver.findElements(By.cssSelector("check-box"));

    // Setting Column Selection
    checkboxes.get(1).click();
    List<WebElement> radiobuttons = driver.findElements(By.cssSelector("radio-button"));

    // Setting Single Interval Selection
    radiobuttons.get(2).click();

    WebElement table = driver.findElement(By.cssSelector("table"));
    int colCount = new Integer(table.getAttribute("columnCount"));
    AssertJUnit.assertEquals(5, colCount);
    for (int colNum = 0; colNum < colCount; colNum++) {
        assertClickOnColumn(table, colNum);
    }

    assertShiftClickSingleIntSelection(table, 1, 3, "1, 2, 3");
}
 
Example 6
Project: saladium   File: SaladiumDriver.java   View Source Code Vote up 6 votes
@Override
public void etrePlein(String type, String selector) {
    this.logger.info("etrePlein(String id)");
    By locator = BySelec.get(type, selector);
    WebElement elem = wait.until(ExpectedConditions.presenceOfElementLocated(locator));

    if (elem.getAttribute("value") != null) {
        if (elem.getAttribute("value").toString().trim().isEmpty()) {
            Assert.fail("l'élément ne devrait pas être vide!");
        }
    } else {
        if (elem.getText().trim().isEmpty()) {
            Assert.fail("l'élément ne devrait pas être vide!");
        }
    }
}
 
Example 7
Project: kheera   File: AbstractPage.java   View Source Code Vote up 5 votes
@Override
public String getText(WebElement w) {
	String returnValue = "";
	try {
		if (null != w.getAttribute("value")) {
			returnValue += w.getAttribute("value");
		} else if (null != w.getText()) {
			returnValue += w.getText();
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return returnValue;
}
 
Example 8
Project: hippo   File: SiteSteps.java   View Source Code Vote up 5 votes
private String getElementText(WebElement element) {
    if (element.getTagName().equals("input")) {
        return element.getAttribute("value");
    }

    return element.getText();
}
 
Example 9
Project: hippo   File: SiteSteps.java   View Source Code Vote up 5 votes
@Then("I can download(?: following files)?:")
public void iCanDownload(final DataTable downloadTitles) throws Throwable {
    for (List<String> downloadLink : downloadTitles.asLists(String.class)) {
        String linkText = downloadLink.get(0);
        String linkFileName = downloadLink.get(1);

        WebElement downloadElement = sitePage.findElementWithTitle(linkText);

        assertThat("I can find download link with title: " + linkText,
            downloadElement, is(notNullValue()));

        String url = downloadElement.getAttribute("href");
        assertEquals("I can find link with expected URL for file " + linkFileName, URL + urlLookup.lookupUrl(linkFileName), url);

        if (acceptanceTestProperties.isHeadlessMode()) {
            // At the moment of writing, there doesn't seem to be any easy way available to force Chromedriver
            // to download files when operating in headless mode. It appears that some functionality has been
            // added to DevTools but it's not obvious how to trigger that from Java so, for now at least,
            // we'll only be testing file download when operating in a full, graphical mode.
            //
            // See bug report at https://bugs.chromium.org/p/chromium/issues/detail?id=696481 and other reports
            // available online.
            log.warn("Not testing file download due to running in a headless mode, will just check link is present.");
        } else {
            // Trigger file download by click the <a> tag.
            sitePage.clickOnElement(downloadElement);

            final Path downloadedFilePath = Paths.get(acceptanceTestProperties.getDownloadDir().toString(),
                linkFileName);

            waitUntilFileAppears(downloadedFilePath);
        }
    }
}
 
Example 10
Project: ats-framework   File: RealHtmlElementState.java   View Source Code Vote up 5 votes
private void highlightElement(
                               boolean disregardConfiguration ) {

    if (webDriver instanceof PhantomJSDriver) {
        // it is headless browser
        return;
    }

    if (disregardConfiguration || UiEngineConfigurator.getInstance().getHighlightElements()) {

        try {
            WebElement webElement = RealHtmlElementLocator.findElement(element);
            String styleAttrValue = webElement.getAttribute("style");

            JavascriptExecutor js = (JavascriptExecutor) webDriver;
            js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                             webElement,
                             "background-color: #ff9; border: 1px solid yellow; box-shadow: 0px 0px 10px #fa0;"); // to change text use: "color: yellow; text-shadow: 0 0 2px #f00;"
            Thread.sleep(500);
            js.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                             webElement,
                             styleAttrValue);
        } catch (Exception e) {
            // swallow this error as highlighting is not critical
        }
    }
}
 
Example 11
Project: marathonv5   File: JTableRowSelectionTest.java   View Source Code Vote up 5 votes
public void rowSelectionSingleInterval() throws Throwable {
    driver = new JavaDriver();
    List<WebElement> radiobuttons = driver.findElements(By.cssSelector("radio-button"));

    // Setting Single Interval Selection
    radiobuttons.get(2).click();
    WebElement table = driver.findElement(By.cssSelector("table"));
    int rowCount = new Integer(table.getAttribute("rowCount"));
    AssertJUnit.assertEquals(5, rowCount);
    for (int rowNum = 0; rowNum < rowCount; rowNum++) {
        assertClickOnRow(table, rowNum);
    }

    assertShiftClickSingleIntSelection(table, 1, 3, "1, 2, 3");
}
 
Example 12
Project: ats-framework   File: HtmlFileBrowse.java   View Source Code Vote up 5 votes
/**
*
* @param webDriver {@link WebDriver} instance
* @param value the file input value to set
*/
protected void setFileInputValue( WebDriver webDriver, String value ) {

    String locator = this.getElementProperties()
                         .getInternalProperty(HtmlElementLocatorBuilder.PROPERTY_ELEMENT_LOCATOR);

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

    WebElement element = null;

    if (!StringUtils.isNullOrEmpty(css)) {
        element = webDriver.findElement(By.cssSelector(css));
    } else {
        element = webDriver.findElement(By.xpath(locator));
    }

    try {
        element.sendKeys(value);
    } catch (ElementNotVisibleException enve) {

        if (!UiEngineConfigurator.getInstance().isWorkWithInvisibleElements()) {
            throw enve;
        }
        // try to make the element visible overriding some CSS properties
        // but keep in mind that it can be still invisible using another CSS and/or JavaScript techniques
        String styleAttrValue = element.getAttribute("style");
        JavascriptExecutor jsExec = (JavascriptExecutor) webDriver;
        try {
            jsExec.executeScript("arguments[0].setAttribute('style', arguments[1]);",
                                 element,
                                 "display:'block'; visibility:'visible'; top:'auto'; left:'auto'; z-index:999;"
                                          + "height:'auto'; width:'auto';");
            element.sendKeys(value);
        } finally {
            jsExec.executeScript("arguments[0].setAttribute('style', arguments[1]);", element,
                                 styleAttrValue);
        }

    } catch (InvalidElementStateException e) {
        throw new SeleniumOperationException(e.getMessage(), e);
    }
}
 
Example 13
Project: teasy   File: IETestUtils.java   View Source Code Vote up 4 votes
public static boolean isDisabledElement(WebElement element){
    return element.getAttribute("disabled") != null && element.getAttribute("disabled").equals("true");
}
 
Example 14
Project: phoenix.webui.framework   File: SeleniumValueEditor.java   View Source Code Vote up 4 votes
/**
 * 填入值,如果目标元素有readonly,则不做任何操作
 * @param ele 目标元素
 * @param value 要填入的值,null会当作空字符串
 * @param append 是否追加
 */
private void fillValue(Element ele, Object value, boolean append)
{
	if(value == null)
	{
		value = "";
	}

	WebElement webEle = searchStrategyUtils.findStrategy(WebElement.class, ele).search(ele);
	if(webEle != null)
	{
		String readonlyAttr = webEle.getAttribute("readonly");
		if(StringUtil.isNotBlank(readonlyAttr))
		{
			logger.warn("{} is readonly, will do not call method setValue.", webEle.toString());
			return;
		}
		
		String valueStr = value.toString();
		try
		{
			fill(webEle, valueStr, append);
		}
		catch(WebDriverException e)
		{
			if(e.getMessage().contains("is not clickable at point"))
			{
				((JavascriptExecutor) engine.getDriver()).executeScript("arguments[0].scrollIntoView();", webEle);

				fill(webEle, valueStr, append);
			}
			else
			{
				e.printStackTrace();
			}
		}
	}
	else
	{
		logger.error(String.format("can not found element [%s].", ele));
	}
}
 
Example 15
Project: QA_Begin   File: TestContactDoq.java   View Source Code Vote up 4 votes
@Test
    public void cadastro() throws InterruptedException {

        WebDriverWait wait = new WebDriverWait(driver, 30);

        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Name")));
        WebElement name = driver.findElement(By.id("Name"));
        name.sendKeys("Vitor Cardoso");

        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Email")));
        WebElement email = driver.findElement(By.id("Email"));
        email.sendKeys(("[email protected]"));

        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Site")));
        WebElement site = driver.findElement(By.id("Site"));
        site.sendKeys("www.doqconsulting.com.br");

        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Subject")));
        WebElement assunto = driver.findElement(By.id("Subject"));
        assunto.sendKeys("Teste Selenium com assert");

        wait.until(ExpectedConditions.presenceOfElementLocated(By.id("Message")));
        WebElement message = driver.findElement(By.id("Message"));
        message.sendKeys
                ("Gostaria de saber mais sobre a DOQ Consulting e como podemos ajudá-lo? Envie sua mensagem pelo site ou em nossas redes sociais.");

        // SUBMIT AND ASSERT
        name.submit();
        String respname = name.getAttribute("value");
        Assert.assertEquals(respname,"Vitor Cardoso");

        email.submit();
        String resp = email.getAttribute("value");
        Assert.assertEquals(resp,"[email protected]");

        site.submit();
        String respsite = site.getAttribute("value");
        Assert.assertEquals(respsite,"www.doqconsulting.com.br");

        assunto.submit();
        String respassunto = assunto.getAttribute("value");
        Assert.assertEquals(respassunto,"Teste Selenium com assert");

        message.submit();
        String respmsg = message.getAttribute("value");
        Assert.assertEquals(respmsg,
                "Gostaria de saber mais sobre a DOQ Consulting e como podemos ajudá-lo? Envie sua mensagem pelo site ou em nossas redes sociais.");

        wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("button[class='btn btn-send']")));
        WebElement sendclick = driver.findElement(By.cssSelector("button[class='btn btn-send']"));
        sendclick.click(); /*Código comentado devido ao erro do webdriver com o firefox*/

//        wait.until(ExpectedConditions.presenceOfElementLocated(By.className("col-sm-7 col-sm-offset-1")));
//        WebElement validatemsg = driver.findElement(By.className("col-sm-7 col-sm-offset-1"));
//        String test = validatemsg.getText();
//        Assert.assertEquals(test," *Sua mensagem foi enviada com sucesso, logo mais um de nosso consultores irão avaliar o seu caso e entrar em contato. ");


    }
 
Example 16
Project: Selenium-Foundation   File: ComponentContainer.java   View Source Code Vote up 3 votes
/**
 * Determine if the specified element has the desired value.
 * 
 * @param element target element (input, select)
 * @param value desired value
 * @return 'true' if element has the desired value; otherwise 'false'
 */
private static boolean valueEquals(WebElement element, String value) {
    Objects.requireNonNull(element, "[element] must be non-null");
    
    String exist = element.getAttribute("value");
    return (exist != null) ? exist.equals(value) : (value == null);
}
 
Example 17
Project: NoraUi   File: Step.java   View Source Code Vote up 3 votes
/**
 * Checks if input text contains expected value.
 *
 * @param pageElement
 *            Is target element
 * @param textOrKey
 *            Is the data to check (text or text in context (after a save))
 * @return true or false
 * @throws FailureException
 *             if the scenario encounters a functional error
 */
protected boolean checkInputText(PageElement pageElement, String textOrKey) throws FailureException {
    WebElement inputText = null;
    String value = Context.getValue(textOrKey) != null ? Context.getValue(textOrKey) : textOrKey;
    try {
        inputText = Context.waitUntil(ExpectedConditions.presenceOfElementLocated(Utilities.getLocator(pageElement)));
    } catch (Exception e) {
        new Result.Failure<>(e.getMessage(), Messages.getMessage(Messages.FAIL_MESSAGE_UNABLE_TO_FIND_ELEMENT), true, pageElement.getPage().getCallBack());
    }
    return !(inputText == null || value == null || inputText.getAttribute(VALUE) == null || !value.equals(inputText.getAttribute(VALUE).trim()));
}
 
Example 18
Project: zucchini   File: AssertionStep.java   View Source Code Vote up 3 votes
@Then("^option \"([^\"]*)\" by value from radio button group having (id|name|class|xpath|css) \"([^\"]*)\" should be selected$")
public void radioSelectedValue(String option, String type, String element) {

	WebElement webElement = getWebElement(type, element);

	String value = webElement.getAttribute("value");

	assertEquals(value, option);

}
 
Example 19
Project: mot-automated-testsuite   File: WebDriverWrapper.java   View Source Code Vote up 3 votes
/**
 * Get an attribute of an element.
 *
 * @param id ID of the element.
 * @param attribute Attribute to get.
 * @return Value of the attribute.
 */
public String getAttribute(String id, String attribute) {
    WebElement element = webDriver.findElement(By.id(id));
    String value = element.getAttribute(attribute);

    return value == null ? "" : value;
}
 
Example 20
Project: oscm   File: WebTester.java   View Source Code Vote up 2 votes
/**
 * Reads the value of the element with the given id. This is used for fields
 * that use the value attribute, e.g. input fields.
 *
 * @return the value of the element
 * @throws NoSuchElementException
 *             if element is not present
 */
public String readValue(String id) {
    WebElement element = driver.findElement(By.id(id));
    return element.getAttribute(ATTRIUBTE_VALUE);
}