WebElement In Selenium

Selenium is a popular tool for automating web testing tasks. One of the most important aspects of Selenium is its ability to interact with web pages and elements using the WebElement interface.

In this blog post, we’ll explore the different WebElement commands in Selenium, to help you get started with web testing using Selenium. We’ll cover how to locate elements, interact with them, and check their status. By the end of this post, you’ll have a good understanding of how to use WebElement commands in Selenium for web testing.

What is a WebElement?

A Selenium WebElement is an object that represents a web page element. It is a fundamental class in the Selenium API that offers various methods for interacting with items like clicking on buttons, typing in text fields, and choosing options from dropdown menus.

How to Locate WebElements?

To use Selenium to interact with web components, you must first locate them on the web page. The Selenium WebDriver API provides many Locators for locating elements.

  • By ID
  • By Name
  • By Class Name
  • By Tag Name
  • By Link Text
  • By Partial Link Text
  • By cssSelector
  • By Xpath
Read Our Blog on Web Locators In Selenium for a step-by-step guide on how to use different types of WebLocators.

Interacting with WebElements

Now that you know how to find web elements on a website, let’s look at how to interact with them using WebElement commands. Here are some of the most frequently used WebElement commands while testing web applications:

  • Click():
    The Click() method is used to click on a web element.
    Example:
//Directly calling method with element
driver.findElement(By.id("login-button")).click();

//Store the data in webelement varibale, then call the method
WebElement loginButton = driver.findElement(By.id("login-button"));
loginButton.click();

  • SendKeys():
    The SendKeys() method is used to send text to a web element. Here’s an example of how to enter a username and password:
WebElement usernameField = driver.findElement(By.id("username"));
usernameField.sendKeys("myUsername");

WebElement passwordField = driver.findElement(By.id("password"));
passwordField.sendKeys("myPassword");

  • Clear():
    The Clear() method is used to clear the contents of a text field.
    Example:
WebElement usernameField = driver.findElement(By.id("username"));
usernameField.sendKeys("myUsername");

//Clear the content
usernameField.clear();
  • Select():
    The Select() method is used to select an option from a dropdown menu.
    Example:
WebElement dropdown = driver.findElement(By.id("dropdown"));
Select select = new Select(dropdown);
select.selectByVisibleText("Option 1");
  • Submit():
    The Submit method is used to submit a form.
    Example:
WebElement form = driver.findElement(By.id("login-form"));
form.submit();

Checking Element Status

It’s essential that you’re able to monitor the state of web elements while automating tests with Selenium. This can help verify that your test script interacts with the right elements and performs the necessary actions. These are various techniques for checking the status of web elements:

  • isEnabled():
    The isEnabled() method determines whether or not a web element is currently enabled or disabled. It returns a boolean result in form of True and False
    Example:
WebElement submitButton = driver.findElement(By.id("submit-button"));
boolean isEnabled = submitButton.isEnabled();
  • isDisplayed():
    The isDisplayed() method determines whether or not a web element is now displayed on the page. It returns a boolean result in the form of True and False.
    Example:
WebElement logo = driver.findElement(By.id("logo"));
boolean isDisplayed = logo.isDisplayed();
  • isSelected():
    The isSelected() method determines if a web element, such as a checkbox or radio button, has been selected. It returns a boolean result in the form of True and False.
    Example:
WebElement checkbox = driver.findElement(By.id("checkbox"));
boolean isSelected = checkbox.isSelected();
  • getTagName():
    The getTagName() method is used to get a web element’s tag name. It returns a string value that provides the tag’s name.
    Example:
WebElement header = driver.findElement(By.tagName("h1"));
String tagName = header.getTagName();
  • getText():
    The getText() method is used to get the text from a web element.
    Example:
WebElement welcomeMessage = driver.findElement(By.id("welcome-message"));
String message = welcomeMessage.getText();

  • getCssValue():
    The getCssValue() method is used to get the value of a specific CSS property of a web element. It returns a string value that represents the value of the specified property.
    Example:
WebElement link = driver.findElement(By.tagName("a"));
String color = link.getCssValue("color");
  • getSize():
    The getSize() method is used to get the size of a web element. It returns a Dimension object that contains the height and width of the element.
    Example:
WebElement button = driver.findElement(By.id("submit-button"));
Dimension size = button.getSize();
  • getLocation():
    The getLocation() method is used to get the location of a web element. It returns a Point object that contains the x and y coordinates of the element.
    Example:
WebElement inputField = driver.findElement(By.id("input-field"));
Point location = inputField.getLocation();
  • getRect():
    The getRect() method introduced in selenium 4, it is the combination of getSize() and getLocation() methods that are used to get the size and location of an element on a web page as a Rectangle object. This object contains the x and y coordinates, as well as the width and height of the element.
    Example:
WebElement inputField = driver.findElement(By.id("input-field"));
Rectangle rect = inputField.getRect();

Putting Everything Together in Practical Example

The following example will demonstrate use of all the above Webelements:

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.Point;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;

public class Webelementexample {

	public static void main(String[] args) {

		WebDriver driver = new ChromeDriver();
		driver.get("https://www.selenium.dev/selenium/web/");
		driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));

		// How to click an element
		WebElement Webform = driver.findElement(By.linkText("web-form.html"));
		Webform.click(); // click()

		// How to send data into field
		WebElement Textinput = driver.findElement(By.id("my-text-id"));
		Textinput.sendKeys("Testingmint"); // sendkeys()

		WebElement Password = driver.findElement(By.name("my-password"));
		Password.sendKeys("Blogger"); // sendkeys()

		// How to Clear the data
		WebElement Textarea = driver.findElement(By.xpath("//textarea[@name='my-textarea']"));
		Textarea.sendKeys("Normal Blog");
		Textarea.clear(); // clear()
		Textarea.sendKeys("All in one blog for Software tester");

		// isenabled
		WebElement disablefield = driver.findElement(By.name("my-disabled"));
		boolean isEnabled = disablefield.isEnabled();
		System.out.println("Field Enabled: " + isEnabled);

		// how to select option from dropdown
		WebElement Dropdown = driver.findElement(By.className("form-select"));
		Select select = new Select(Dropdown);
		select.selectByVisibleText("Two"); // select()

		// is checkbox selected
		WebElement checkbox = driver.findElement(By.id("my-check-1"));
		boolean isSelected = checkbox.isSelected();
		System.out.println("Checkbox Selected: " + isSelected);

		// get the color code of color palette
		WebElement link = driver.findElement(By.name("my-colors"));
		String color = link.getCssValue("color");
		System.out.println("Color: " + color);

		WebElement button = driver.findElement(By.tagName("button"));

		// Get height and width of the box using getSize()
		Dimension size = button.getSize();
		System.out.println("Print Height and width using getSize()");
		System.out.println("Width: " + size.width + ", Height: " + size.height);

		// Get x-axis and y-axis of the box using getLocation()
		Point location = button.getLocation();
		System.out.println("Print x-axis and y-axis using getLocation()");
		System.out.println("X-axis: " + location.x + ", Y-axis: " + location.y);

		// get height, width, x-axis and y-axis of box
		Rectangle rect = button.getRect();
		System.out.println("Print width, heigh, x-axis and y-axis using getRect()");
		System.out.println(
				"Width: " + rect.width + ", Height: " + rect.height + "X-axis: " + rect.x + ", Y-axis: " + rect.y);

		// How to submit the Form
		WebElement Form = driver.findElement(By.tagName("form"));
		Form.submit(); // submit()

		// get the text after form submission
		WebElement SubMessage = driver.findElement(By.tagName("h1"));
		String message = SubMessage.getText();
		System.out.println(message);

		// Form Submitted is Displayed
		WebElement Header = driver.findElement(By.tagName("h1"));
		boolean isDisplayed = Header.isDisplayed();
		System.out.println("Form submitted display: " + isDisplayed);

	}

}

Output:

Conclusion

In conclusion, understanding and utilizing WebElement commands in Selenium is crucial for creating effective and reliable automated tests. By learning how to locate and interact with elements on a web page, checking their status, and using various waits and alerts, you can ensure that your automated tests are thorough and catch potential issues before they cause failures.

By using these techniques in combination with Java and other programming languages, you can create powerful and effective automated tests that can save time and effort while improving the quality and reliability of your web applications.