Getting text and attributes in Selenium Java - Build an Automation Script
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.time.Duration; public class GetTextAndAttributesTest { private WebDriver driver; private WebDriverWait wait; @BeforeClass public void setUp() { driver = new ChromeDriver(); wait = new WebDriverWait(driver, Duration.ofSeconds(10)); driver.manage().window().maximize(); } @Test public void testGetTextAndAttributes() { driver.get("http://example.com/sample"); WebElement heading = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("main-heading"))); String headingText = heading.getText(); Assert.assertEquals(headingText, "Welcome to Sample Page", "Heading text does not match"); WebElement submitButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("submit-btn"))); String buttonType = submitButton.getAttribute("type"); Assert.assertEquals(buttonType, "submit", "Button type attribute does not match"); WebElement helpLink = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("help-link"))); String hrefValue = helpLink.getAttribute("href"); Assert.assertEquals(hrefValue, "http://example.com/help", "Link href attribute does not match"); } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
The @BeforeClass method sets up the ChromeDriver and WebDriverWait to wait up to 10 seconds for elements.
The test method navigates to the sample page URL.
It waits explicitly for the heading element to be visible, then gets its text and asserts it matches the expected string.
Similarly, it waits for the submit button and gets its type attribute, asserting it equals 'submit'.
Then it waits for the help link, gets its href attribute, and asserts it matches the expected URL.
The @AfterClass method closes the browser to clean up.
This approach uses explicit waits to avoid timing issues, uses By.id locators for clarity and speed, and TestNG assertions for clear validation messages.
Now add data-driven testing with 3 different sets of expected heading text, button type, and link href values