Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3525

Difference Between getText() and getAttribute() in Selenium WebDriver

$
0
0
Contact Us Featured

1. Introduction

In this article, we’ll look at ways to get the value of attributes of web elements on a web page using Selenium WebDriver with Java. We’ll also explore the differences between getText() and getAttribute() methods.

For testing, we’ll use JUnit and Selenium to open https://www.baeldung.com/contact. The page has a visible input field called “Your Name*”. We’ll use this field to show the difference between getText() and getAttribute().

2. Dependencies

First, we add the selenium-java and Junit dependencies to our project in the pom.xml:

<dependency> 
    <groupId>org.seleniumhq.selenium</groupId> 
    <artifactId>selenium-java</artifactId> 
    <version>4.18.1</version>
</dependency>
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.9.2</version> <scope>test</scope>
</dependency>
<dependency>
    <groupId>io.github.bonigarcia</groupId>
    <artifactId>webdrivermanager</artifactId>
    <version>5.7.0</version>
</dependency>

3. Configuration

Next, we need to configure WebDriver. In this example, we’ll use its Chrome implementation after downloading its latest version:

@BeforeEach
public void setUp() {
    WebDriverManager.chromedriver().setup();
    driver = new ChromeDriver();
}

We’re using a method annotated with @BeforeEach to do the initial setup before each test. Next, we use WebDriverManager to get the Chrome Driver without explicitly downloading and installing it. This allows us to use the Selenium Web Driver without the need to use the absolute path of the driver. We still need the Chrome browser installed on the target machine where we’ll run this code.

When the test finishes, we should close the browser window. We can do this by placing the driver.close() statement inside a method annotated with @AfterEach. This ensures that it’ll be executed even if the test fails:

@AfterEach
public void cleanUp() {
    driver.close();
}

4. Find Visible Text getText()

Now that the scaffolding is ready, we must add code to identify the relevant web element. There are several ways to help Selenium pick an element such as by using ID, CSS selector, Class name, Xpath, etc.

The contact page has a visible input field called “Your Name*”. We use the browser development tools (inspect element) to choose the HTML code relevant to this field:

<label> Your Name*<br>
<span class="wpcf7-form-control-wrap" data-name="your-name">
<input size="40" maxlength="400" class="wpcf7-form-control
          wpcf7-text wpcf7-validates-as-required" aria-required="true" aria-invalid="false"
          value="" type="text" name="your-name">
</span>
</label>

4.1. Test for Visible Text

We’re interested in the visible text on the label, i.e. “Your Name”. We can get hold of the visible text using the getText() method on a selenium Element. Now, as is evident from the HTML excerpt, this label element also contains a lot of other code apart from the visible text. However, getText() only gets the text that would be visible to us when we view the page on a browser.

To illustrate this, we write a test that confirms that the page contains a field with the visible text “Your Name”. First, we define some constants:

private static final String URL = "https://www.baeldung.com/contact";
private static final String LABEL_XPATH = "//label[contains(text(),'Your Name')]";
private static final String LABEL_TEXT = "Your Name*";
private static final String INPUT_XPATH = "//label[contains(text(),'Your Name')]//input";

Then we add a test method to confirm that the text that is returned by getText() exactly matches the visible text “Your Name*”:

@Test
public void givenBaeldungContactPage_whenFoundLabel_thenContainsText() {
    driver.get(URL);
    WebElement inputElement = driver.findElement(By.xpath(LABEL_XPATH));
    assertEquals(LABEL_TEXT, inputElement.getText());
}

4.2. Test for No Visible Text

Further, we also note that the input element has no visible text, and therefore, when we run the getText() method on this element, we expect an empty String. We add another test method to confirm this:

@Test
public void givenBaeldungContactPage_whenFoundNameInput_thenContainsText() {
    driver.get(URL);
    WebElement inputElement = driver.findElement(By.xpath(INPUT_XPATH));
    assertEquals("", inputElement.getText());
}

Now that we understand the workings of getText(), we review the use of getAttribute().

5. Find Attribute Value getAttribute()

We now examine the usage of getAttribute() on a web element. This time we focus on the input field with the name “your-name”. It has many attributes, such as size, maxlength, value, type, and name. The getAttribute() method on a web element is expected to return the value associated with an attribute passed as the method parameter provided such an attribute exists on the web element. If no such attribute exists, the method returns a null value.

e.g. If we review the HTML excerpt from the label element, we notice that the input element has an attribute name with the value “your-name” and another attribute maxlength with the value 400.

When writing tests that involve checking these attributes, we use the getAttribute method. We first define constants for values we want to check:

private static final String INPUT_NAME = "your-name";
private static final String INPUT_LENGTH = "400";

5.1. Test to Get Value of an Attribute

Let’s add a couple of tests to check the attribute values for the attributes called name and maxlength:

@Test
public void givenBaeldungContactPage_whenFoundNameInput_thenHasAttributeName() {
    driver.get(URL);
    WebElement inputElement = driver.findElement(By.xpath(INPUT_XPATH));
    assertEquals(INPUT_NAME, inputElement.getAttribute("name"));
}
@Test
public void givenBaeldungContactPage_whenFoundNameInput_thenHasAttributeMaxlength() {
    driver.get(URL);
    WebElement inputElement = driver.findElement(By.xpath(INPUT_XPATH));
    assertEquals(INPUT_LENGTH, inputElement.getAttribute("maxlength"));
}

5.2. Test to Get Value of Non-Existent Attribute

Next, we write a test to confirm that when we look for a non-existent attribute X using getAttribute(), it returns a null value:

@Test
public void givenBaeldungContactPage_whenFoundNameInput_thenHasNoAttributeX() {
    driver.get(URL);
    WebElement inputElement = driver.findElement(By.xpath(INPUT_XPATH));
    assertNull(inputElement.getAttribute("X"));
}

6. Conclusion

In this article, we’ve learned how to get the visible text and the value of attributes of web elements on a web page using Selenium WebDriver with Java. The getText() only shows the plain text as visible on an element when the web page is viewed on a browser whereas getAttribute() allows us to get the values against many different attributes on a web element.

The general flow is to use Selenium selectors to identify the web element of interest and then to use one of the methods getText() or getAttribute() to get more details about a web element.

We also added a few sample tests to demonstrate the usage of these methods in automated tests. As always, the source for the article is available over on GitHub.

       

Viewing all articles
Browse latest Browse all 3525

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>