Reading Text and Attributes

getText, getAttribute, getDomAttribute, getDomProperty

<input id="qty" type="number" value="1">
<a id="product-link" href="/products/101">Nike Revolution 7</a>
<span id="cart-count" class="badge">3</span>
MethodReturnsExample result
getText()visible text of the element"3" for #cart-count
getDomAttribute("href")the attribute as written in HTML"/products/101"
getDomProperty("href")the live DOM property"https://shopease.example.com/products/101"
getAttribute("value")property if it exists, else attribute (older, mixed behaviour)current value of #qty, e.g. "2" after typing
getTagName(), getCssValue("color")tag name, computed CSS"span", "rgba(220, 53, 69, 1)"

Reading a Text Box

WebElement qty = driver.findElement(By.id("qty"));
qty.clear();
qty.sendKeys("2");
System.out.println("getText: [" + qty.getText() + "]");               // inputs have no text
System.out.println("value:   " + qty.getDomProperty("value"));
System.out.println("html attr: " + qty.getDomAttribute("value"));

Example

Output:

Run QuantityTest.main()

Example output

getText: []
value:   2
html attr: 1

Note: getText() on an <input> is always empty. Read what the user typed with getDomProperty("value"). In Selenium 4, prefer getDomAttribute / getDomProperty; getAttribute still works but mixes the two.

Turning Page Text into Numbers

Example

Texts read with getText() usually need cleaning before you can compare them. Here are values as they would come from ShopEase:

public class Main {
    static int toInt(String text) {
        return Integer.parseInt(text.replaceAll("[^0-9]", ""));
    }

    public static void main(String[] args) {
        String cartBadge = " 3 ";
        String subtotal = "Subtotal (3 items): ₹3,897";
        String priceEach = "₹1,299";

        int count = toInt(cartBadge);
        int total = toInt(subtotal.substring(subtotal.indexOf("₹")));
        System.out.println("count=" + count + ", total=" + total + ", each=" + toInt(priceEach));
        System.out.println("Total equals 3 x each? " + (total == 3 * toInt(priceEach)));
    }
}

Output

count=3, total=3897, each=1299
Total equals 3 x each? true