Software Development

Selenium WebDriver: submit() vs click()

Selenium WebDriver provides several ways to interact with elements on a web page. Two commonly used methods are click() and submit(). Although both methods can be used to submit a form in certain situations, they work differently and should not be treated as interchangeable.

1. Overview

Automated web testing frequently requires interacting with HTML forms. A typical form may contain text fields, dropdowns, checkboxes, radio buttons, and one or more buttons used to submit or perform actions on the form. Selenium WebDriver allows Java applications to interact with these elements programmatically, making it possible to automate common user workflows such as logging in, searching for information, submitting orders, or completing registration forms. When a test needs to submit a form, two commonly used Selenium methods are click() and submit(). Although both can result in a form being submitted, they represent different types of operations:

  • Calling click() on a button or other clickable element simulates an interaction with that specific element.
  • Calling submit() on an element submits the form associated with that element.

This distinction becomes important when the page contains JavaScript event handlers, multiple submit buttons, client-side validation, nested elements, or different actions associated with individual buttons. Choosing the appropriate method helps ensure that the automated test represents the intended application behavior.

1.1 What is Selenium?

Selenium is an open-source framework used to automate web browsers. It supports multiple programming languages, including Java, Python, JavaScript, C#, and Ruby. Selenium WebDriver is the primary API used for browser automation and provides a programming interface for interacting with elements in a web page. Using WebDriver, a test can locate elements in the page’s DOM and perform actions that are similar to those performed by a user. Common operations include:

  • Entering text into input fields
  • Clicking buttons and links
  • Selecting options from dropdowns
  • Selecting checkboxes and radio buttons
  • Submitting forms
  • Reading text and element attributes
  • Navigating between pages
  • Executing JavaScript when required

Selenium is primarily focused on browser interaction rather than directly testing the application’s internal Java code. This makes it useful for end-to-end and UI automation, where the test needs to verify how the application behaves from a browser user’s perspective.

1.2 How Selenium Works?

At a high level, a Java Selenium test communicates with a browser through a browser driver that implements the WebDriver protocol. The test uses the Selenium WebDriver API to locate elements and request browser actions, while the browser driver translates those requests into operations that the browser can execute. For example, when a Java program executes driver.findElement(By.id("loginButton")).click();, Selenium first locates the element with the specified ID and then instructs the browser to perform a click operation on that element. The overall flow can be represented as Java Test → Selenium WebDriver API → Browser Driver → Web Browser → Web Page / DOM. The important point is that WebDriver works with the browser and its DOM rather than simply manipulating HTML as a text document. This allows Selenium tests to interact with elements in a way that closely resembles real browser interactions.

1.3 Understanding click()

The click() method is available through Selenium’s WebElement interface and is used to perform a click operation on a specific element.

WebElement button = driver.findElement(By.id("loginButton"));

button.click();

The method represents an interaction with the particular element. If the element is a submit button, clicking it will normally cause the associated form to be submitted. However, the primary purpose of click() is to interact with the element itself. This distinction is important when a button has additional behavior associated with its click event. For example, a button may execute JavaScript validation, display a confirmation message, update the page, or trigger another application action before or instead of submitting the form. Therefore, click() is generally appropriate when the test is intended to reproduce the action a user would perform on the page.

1.3.1 When Should You Use click()?

Use click() when you want to reproduce an actual user interaction with an element. For example, driver.findElement(By.id("loginButton")).click(); can be used to locate and click a specific Login button. This is generally the preferred approach when the test is intended to verify UI behavior because it closely represents what a real user would do. It is especially appropriate when the user is expected to click a button, the button contains JavaScript click behavior, the test needs to verify the actual UI interaction, the element is a link or another clickable control, or different buttons perform different actions.

1.4 Understanding submit()

Selenium’s submit() method is also available through WebElement and is specifically intended for submitting an HTML form.

WebElement username = driver.findElement(By.name("username"));

username.submit();

When submit() is called, Selenium attempts to submit the form associated with the element. The element does not necessarily need to be the submit button itself; it can be another element that belongs to the form. For example, if a username input field belongs to a login form, calling submit() on that input can submit the associated form:

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

This makes submit() useful when the intention of the test is specifically to submit a form rather than to simulate a click on a particular button. However, submit() should not automatically be considered a replacement for click(). If a form contains multiple buttons with different actions or relies on button-specific JavaScript behavior, clicking the intended button may provide a more accurate representation of the application’s actual user flow.

1.4.1 When Should You Use submit()?

Use submit() when your primary intention is to submit a form and you do not specifically need to simulate clicking a particular button. For example, driver.findElement(By.id("username")).submit(); submits the form associated with the username field. This can be convenient when the form contains many fields and you already have a reference to one of those fields.

2. Code Example Covering click() and submit()

2.1 Example HTML Page

Consider the following simple HTML page containing a login form. The form includes username and password fields along with a submit button, providing a basic example for demonstrating the difference between Selenium’s click() and submit() methods.

<!DOCTYPE html>
<html>
   <head>
      <title>Login Page</title>
   </head>
   <body>
      <h1>Login</h1>

      <form id="loginForm" action="success.html" method="get">
         <label for="username">Username:</label>
         <input type="text" id="username" name="username" />

         <br /><br />

         <label for="password">Password:</label>
         <input type="password" id="password" name="password" />

         <br /><br />

         <button type="submit" id="loginButton">Login</button>
      </form>
   </body>
</html>

The page defines a login form with the ID loginForm and specifies success.html as its submission target using the action attribute. The username and password fields allow the test to enter login credentials, while the button element is defined as a submit button using type="submit". Since all three controls belong to the same form, Selenium can submit the form either by clicking the loginButton with click() or by calling submit() on an element such as the username field.

2.2 Maven Dependency

The following Maven dependency adds Selenium WebDriver to a Java project. Use the Selenium version that matches the requirements of your project.

<dependency>
	<groupId>org.seleniumhq.selenium</groupId>
	<artifactId>selenium-java</artifactId>
	<version>4.x.x</version>
</dependency>

Replace 4.x.x with the Selenium version used by your project.

2.3 Complete Java Example

2.3.1 Using click()

The following example opens the login page, enters values into the username and password fields, and submits the form by clicking the Login button. It also prints the URL after the form is submitted and ensures that the browser is closed using a finally block.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumSubmitVsClickExample {

  public static void main(String[] args) {
  
    WebDriver driver = new ChromeDriver();

    try {
      driver.get("file:///path/to/login.html");
      /*
       * Example 1: Submit the form using click()
       */
      driver.findElement(By.id("username")).sendKeys("john");
      driver.findElement(By.id("password")).sendKeys("secret");
      driver.findElement(By.id("loginButton")).click();
      System.out.println("Form submitted using click(): " + driver.getCurrentUrl());
    } finally {
      driver.quit();
    }
  }
}

The example first creates a ChromeDriver instance and navigates to the login page using driver.get(). It then locates the username and password fields by their IDs and enters the test values using sendKeys(). Finally, it locates the Login button and calls click(), which submits the form because the button is defined with type="submit". The current URL is then printed to verify the navigation, and driver.quit() closes the browser after the test completes.

Form submitted using click(): file:///path/to/success.html?username=john

The output shows that the form was submitted successfully and the browser navigated to the URL specified by the form’s action attribute. Because the form uses the GET method, the username is included as a query parameter in the resulting URL. The exact URL depends on the location of the HTML files and the form configuration.

2.3.2 Using submit()

Now consider the same form, but instead of locating and clicking the submit button, the form can be submitted directly through an element that belongs to it. The following example uses the username field to submit the associated login form.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class SeleniumSubmitExample {

  public static void main(String[] args) {

    WebDriver driver = new ChromeDriver();

    try {
      driver.get("file:///path/to/login.html");
      driver.findElement(By.id("username")).sendKeys("john");
      driver.findElement(By.id("password")).sendKeys("secret");
      /*
       * Submit the form associated with the username field.
       */
      driver.findElement(By.id("username")).submit();
      System.out.println("Form submitted using submit(): " + driver.getCurrentUrl());
    } finally {
      driver.quit();
    }
  }
}

The example first opens the login page and enters values into the username and password fields. Instead of locating the Login button, it calls submit() on the username field. Because the username field belongs to the login form, Selenium submits that associated form. The current URL is then printed to verify the result, and the finally block ensures that the browser is closed after execution.

Form submitted using submit(): file:///path/to/success.html?username=john

The output is similar to the click() example because both approaches submit the same HTML form. The key difference is how the submission is initiated: click() interacts with the Login button, while submit() submits the form associated with the username field.

3. Conclusion

Selenium WebDriver’s click() and submit() methods can both result in a form being submitted, but they represent different operations. The click() method interacts with a specific element and is the better choice when you want to simulate the way a real user interacts with the page. It can be used with buttons, links, and other clickable elements. The submit() method is specifically concerned with form submission. It can be called on an element associated with a form, allowing the form to be submitted without explicitly locating and clicking its submit button.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button