logo logo

Selenium WebElement Methods (Chapter 2)

main post image

In this 2nd Selenium Method Categories article series, we will look at the WebElement Method category. A WebElement represents an HTML element. We see the elements as buttons, text, links, images, etc. on a web page. Therefore, the WebElement Method category can perform an action on everything visible on a web page. The other Selenium Method Categories are:

  1. Browser Methods perform actions on a browser
  2. Navigation Methods loads a web page, refreshes a web page, or moves backward and forward in our browser’s history
  3. Wait Methods pause between execution statements
  4. Switch Methods switch to alerts, windows, and frames. An alert is also known as a pop-up

By the end of this article, you will read about findElement, click, sendKeys, getText, getAttribute, clear, isDisplayed, and isEnabled. The code from this article is located on GitHub: https://github.com/RexJonesII/TestProject-TestNG.

Tutorial Chapters

  1. Selenium Browser Methods (Chapter 1)
  2. You’re here → WebElement Methods (Chapter 2)
  3. Navigation Methods (Chapter 3) – Coming Soon
    • back
    • forward
    • refresh
    • to
  4. Wait Methods (Chapter 4) – Coming Soon
    • pageLoadTimeOut
    • ImplicitWait
    • ExplicitWait
    • FluentWait
  5. Switch Methods (Chapter 5) – Coming Soon
    • Switch Methods for Frames
    • Switch Methods for Alerts
    • Switch Methods for Windows

What Is A WebElement?

A WebElement is sometimes called an element. It symbolizes an HTML element within an HTML document. HTML stands for HyperText Markup Language which instructs the browser how to display content. The HTML element contains a start tag, end tag and content between both tags.

For example, in the following screenshot from TestProject’s Blog homepage, the DOM “black arrow” shows start tag <h1>, end tag </h1>, and content “Test Automation Blog”. As a result, the browser displays Test Automation Blog as header 1 “green arrow” on the web page:

TestProject Test Automation Blog

In the org.openqa.selenium package, all operations/actions interacting with the web page are performed through the WebElement Interface. We can perform an action such as getText() on Test Automation Blog “green arrow”.

Selenium WebElement Method

In alphabetical order, the following 16 methods carry out actions on the web page via WebElement Interface:

  1. clear
  2. click
  3. findElement
  4. findElements
  5. getAttribute
  6. getCssValue
  7. getLocation
  8. getRect
  9. getSize
  10. getTagName
  11. getText
  12. isDisplayed
  13. isEnabled
  14. isSelected
  15. sendKeys
  16. submit

findElement()

The findElement() method is the most important WebElement method. It’s important because we have to first find the WebElement before performing an action on the WebElement. If there are multiple elements with the same locator value then findElement() locates the first WebElement. Therefore, it’s best to find an element by a unique locator value.

A locator value is a value identified by 1 of 8 Selenium Locators (id, name, className, xpath, cssSelector, linkText, partialLinkText, tagName). We are going to build from the previous blog article Selenium Browser Methods. In that article, we loaded TestProject’s Blog page and retrieved the page title:

@Test
public void demoBrowserMethods () {
  driver.get("https://blog.testproject.io/");	
  
  String urlTestProject = driver.getCurrentUrl();
  System.out.println("What Is Test Project's Current URL? " + urlTestProject);
  
  String titleTestProject = driver.getTitle();
  System.out.println("What Is Test Project's Page Title? " + titleTestProject);
}

Now, let’s find the Login WebElement link on TestProject’s Blog page:

@Test
  public void demoWebElementMethods () {
     WebElement linkLogin = driver.findElement(By.id("menu-item-7501"));		 
  }

The findElement() method found Login link using a By locating mechanism, an id locator with a value of menu-item-7501. A NoSuchElementException would have been returned if there was no matching element.

Note: findElements() method locates all elements with a specific locator value.

click()

The click() method is used to click an element. However, to click an element, it must be visible with a height and width larger than zero (0). The Login link is visible and will be clicked after writing linkLogin.click().

TestProject Login

@Test
  public void demoWebElementMethods () {
     WebElement linkLogin = driver.findElement(By.id("menu-item-7501"));		 
     linkLogin.click();
  )

sendKeys()

Next, we attempt to log into TestProject by typing a Username and Password. With Selenium, we replicate typing text using the sendKeys() method. [email protected] is the parameter for Username sendKeys and FakePassword is the parameter for Password sendKeys.

driver.findElement(By.id("username")).sendKeys("[email protected]");
driver.findElement(By.id("password")).sendKeys("FakePassword");	
driver.findElement(By.id("tp-sign-in")).click();

TestProject Sign In TestProject Sign In

After clicking the Sign in button, an error message is displayed due to an incorrect password. The error message states “Invalid username or password”.

Note: We can view all blogs from TestProject without logging into the web site.

getText()

The getText() method returns visible text of an element. An element such as the error message is a good candidate. Let’s get the value since I was unable to sign in. The following code implements getText() and assigns the value to String errorMessage. Afterwards, the next line prints the errorMessage:

String errorMessage = driver.findElement(By.id("tp-message-error")).getText();
System.out.println("What Is The Error Message? " + errorMessage);

getText() method

The Console shows “What Is The Error Message? Invalid username or password”.

getAttribute()

The getAttribute() method returns an attribute’s current value or null if there isn’t a value. Attributes supply additional information about an HTML element. Usually, they come in name-value pairs and specified in the start tag.

getAttribute() method

The input starting tag contains placeholder=”password”. Attribute name is placeholder while password is the value “black arrow”. The web page shows a placeholder value “green arrow” in the password text field. Here’s a code snippet that gets and prints the attribute value:

String holderPassword = driver.findElement(By.id("password")).getAttribute("placeholder");
System.out.println("Which Sign In Credential Is Incorrect? " + holderPassword);

The getAttribute() method has placeholder as a parameter because that’s the attribute’s name and assign it to String holderPassword. Next, there is a print statement to print the value of holderPassword:

getAttribute() method

The Console shows “Which Sign In Credential Is Incorrect? password”

clear()

The clear() method clears a value from the text entry field. Username “[email protected]” has a value but will get cleared using clear().

driver.findElement(By.id("username")).clear();

isDisplayed()

The isDisplayed() method returns a boolean value by determining if an element is displayed or not displayed. A boolean value is true or false (true = Yes / false = No). The following code snippet implements isDisplayed() method and assigns the value to boolean linkSignUpForFree. We are going to print if the link is displayed or not displayed. If the link is displayed then our Test Script will click the Sign up for free link:

WebElement linkSignUpForFree = driver.findElement(By.id("tp-signup-link"));
boolean isSignUpForFreeLinkDisplayed = linkSignUpForFree.isDisplayed();
System.out.println("Is The Sign Up For Free Link Displayed? " + isSignUpForFreeLinkDisplayed);
linkSignUpForFree.click();

isDisplayed() method

The Console shows “Is The Sign Up For Free Link Displayed? true”.

isEnabled()

The isEnabled() method returns true if an element is enabled and false if an element is disabled. After clicking the Sign up for free link, the next page shows a disabled Sign Up button. Let’s verify the button is disabled on the Create your free account page:

boolean isSignUpButtonEnabled = driver.findElement(By.id("tp-sign-up")).isEnabled();
System.out.println("Is The Sign Up Button Enabled? " + isSignUpButtonEnabled);

TestProject Free Signup Page

isEnabled() method

The Console shows “Is The Sign Up Button Enabled? false”.

Navigation Methods will be the next article in this series of Selenium Method Categories. Stay tuned! 😎

 

Rex Jones II

About the author

Rex Jones II

Rex Jones II has a passion for sharing knowledge about testing software. His background is development but enjoys testing applications.

Rex is an author, trainer, consultant, and former Board of Director for User Group: Dallas / Fort Worth Mercury User Group (DFWMUG) and member of User Group: Dallas / Fort Worth Quality Assurance Association (DFWQAA). In addition, he is a Certified Software Tester Engineer (CSTE) and has a Test Management Approach (TMap) certification.

Recently, Rex created a social network that demonstrate automation videos. In addition to the social network, he has written 6 Programming / Automation books covering VBScript the programming language for QTP/UFT, Java, Selenium WebDriver, and TestNG.

Join TestProject Community

Get full access to the world's first cloud-based, open source friendly testing community. Enjoy TestProject's end-to-end test automation Platform, Forum, Blog and Docs - All for FREE.

Join Us Now  

Leave a Reply

popup image

Selenium for Teams

Sharing and distributing Selenium tests has never been so easy! With TestProject's FREE Selenium based platform, you can finally create awesome tests with the freedom to collaborate with your team effortlessly.
Sign Up Now right arrow
FacebookLinkedInTwitterEmail