The Wayback Machine - https://web.archive.org/web/20240726054909/https://www.geeksforgeeks.org/how-to-submit-a-form-using-selenium/
Open In App

How to Submit a Form using Selenium?

Last Updated : 04 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Selenium is a great tool when it comes to testing the User interface of websites. Because it has so many features like web driver it allows us to write the scripts in different programming languages like Java, Python, C#, and Ruby. We can write scripts concerning different browsers including the major browsers like Chrome and Firefox. Submitting the form is the major task we want to do because to test different scenarios of user’s input and look at the result is very important. In HTML, there is a set of input types, and testing major of them is a difficult task but we can do this by writing a simple script that will load the site and do the major tasks.

Strategy to Submit Form

So, to test the form we require two main steps:

  1. Finding the element in the HTML code: We can use ID, class, XPath, and many more.
  2. Apply the operation on the field: We can write, click, and read the field or the element.

So, We will first find all the fields in the forms using their id or class whatever is available to us. Then for fields, we will send the values and for buttons, we will execute the click function in the code.

Functions for Finding the Element

As discussed we can find the element by many options so let’s have a look at some functions :

1. By Id

Java




WebElement elementById = driver.findElement(By.id("element_id"));


Python




element = driver.find_element(By.ID, "element_id")


C#




IWebElement elementById = driver.FindElement(By.Id("element_id"));


2. By Class

Java




WebElement elementByClassName = driver.findElement(By.className("element_class"));


Python




element = driver.find_element(By.CLASS_NAME, "element_class")


C#




IWebElement elementByClassName = driver.FindElement(By.ClassName("element_class"));


3. By Name

Java




WebElement elementByName = driver.findElement(By.name("element_name"));


Python




element = driver.find_element(By.NAME, "element_name")


C#




IWebElement elementByName = driver.FindElement(By.Name("element_name"));


4. By CSS Selector

Java




WebElement elementByCssSelector = driver.findElement(By.cssSelector("selector"));


Python




element = driver.find_element(By.CSS_SELECTOR, "selector")


C#




IWebElement elementByCssSelector = driver.FindElement(By.CssSelector("selector"));


5. By XPath

Java




WebElement elementByXPath = driver.findElement(By.xpath("//input[@name='example']"));


Python




element = driver.find_element(By.XPATH, "//input[@name='example']")


C#




IWebElement elementByXPath = driver.FindElement(By.XPath("//input[@name='example']"));


These are some of the functions that we can use for finding the elements from the HTML. We can use different functions in different scenarios.

Example

1. Create a Form

We will create the Form which we will be using to try submitting it from the Selenium script.

HTML




// Creating a form and submitting it
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link
      rel="stylesheet"
      integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC"
      crossorigin="anonymous"
    />
    <title>Form</title>
  </head>
  <body>
    <div class="container mt-5 p-5">
      <h1>Form Submission with Selenium</h1>
      <form class="row g-7" id="myForm" onsubmit="submitForm(event)">
        <div class="col-8">
          <br />
  
          <div class="mb-3 row">
            <label for="FirstName" class="col-sm-2 col-form-label"
              >FirstName</label
            >
            <div class="col-sm-10">
              <input type="text" class="form-control" id="FirstName" />
            </div>
          </div>
  
          <div class="mb-3 row">
            <label for="DOB" class="col-sm-2 col-form-label">DOB</label>
            <div class="col-sm-10">
              <input type="date" class="form-control" id="DOB" />
            </div>
          </div>
  
          <div class="mb-3 row">
            <label for="Email" class="col-sm-2 col-form-label">Email</label>
            <div class="col-sm-10">
              <input type="email" class="form-control" id="Email" />
            </div>
          </div>
  
          <div class="mb-3 row">
            <label for="inputNumber" class="col-sm-2 col-form-label"
              >Number</label
            >
            <div class="col-sm-10">
              <input type="number" class="form-control" id="inputNumber" />
            </div>
          </div>
  
          <div class="mb-3 row">
            <label class="col-sm-2 col-form-label" for="Gender">Gender</label>
            <div class="form-check col-sm-2">
              <input
                class="form-check-input"
                type="radio"
                name="Gender"
                id="Male"
                value="Male"
              />
              <label class="form-check-label" for="Male">Male</label>
            </div>
            <div class="form-check col-sm-2">
              <input
                class="form-check-input"
                type="radio"
                name="Gender"
                id="Female"
                value="Female"
              />
              <label class="form-check-label" for="Female">Female</label>
            </div>
          </div>
  
          <button class="btn btn-info col-sm-2" type="submit">Submit</button>
        </div>
      </form>
    </div>
  
    <script>
      function submitForm(event) {
        // Prevent the form from actually submitting
        event.preventDefault();
  
        // Extract form data
        const firstName = document.getElementById("FirstName").value;
        const dob = document.getElementById("DOB").value;
        const email = document.getElementById("Email").value;
        const number = document.getElementById("inputNumber").value;
        const gender = document.querySelector(
          'input[name="Gender"]:checked'
        ).value;
  
        if (!/^\d{10}$/.test(number)) {
          alert("Error");
          return;
        }
  
        // Create a message with the form data
        const message = `First Name: ${firstName}\nDOB: ${dob}\nEmail: ${email}\nNumber: ${number}\nGender: ${gender}`;
  
        // Display an alert with the form data
        alert(message);
  
        document.getElementById("FirstName").value = "";
        document.getElementById("DOB").value = "";
        document.getElementById("Email").value = "";
        document.getElementById("inputNumber").value = "";
        document.querySelector('input[name="Gender"]:checked').checked = false;
      }
    </script>
  </body>
</html>


Explanation:

In this code, we have used text, date, email, number (10 Digits) and Radio button. Writing code for submitting this form will give you an idea of most of the common fields. Also, on submitting the Alert box which shows the submission of the form.

Output:

form

Output Form

2. Code to Submit a Form

Now, as discussed first we will try to get the fields in which all the data will be entered. To get the field we can find it using Id, Class, or CSS Selector. In the following code blocks, we will find the fields using ID and the submit button will be tracked using the CSS Selector.

Java




// Java code to find the fields using ID 
// Submit button will be tracked using the CSS Selector
  
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.Alert;
  
public class Main {
    public static void main(String[] args) 
    {
      // Add External Dependency first to run the application
        System.setProperty("webdriver.chrome.driver", 
                           "path/to/chromedriver");
        WebDriver driver = new ChromeDriver();
  
        driver.get("your-webpage-url");
  
        WebElement firstName = driver.findElement(By.id("FirstName"));
        WebElement dob = driver.findElement(By.id("DOB"));
        WebElement email = driver.findElement(By.id("Email"));
        WebElement inputNumber = driver.findElement(By.id("inputNumber"));
        WebElement maleRadioButton = driver.findElement(By.id("Male"));
  
        firstName.sendKeys("Ram");
        dob.sendKeys("19-01-2001");
        email.sendKeys("ram@example.com");
        inputNumber.sendKeys("1234567890");
        maleRadioButton.click();
  
        driver.findElement(By.cssSelector("button[type='submit']")).click();
          
           Alert alert = driver.switchTo().alert();
        String alertText = alert.getText();
  
        // Check if the alert is open
        if (alertText != null) 
        {
            System.out.println("Alert is open, and the content is: " + alertText);
            // You can accept the alert if needed: alert.accept();
        } 
        else 
        {
            System.out.println("No alert found");
        }      
        driver.quit();
    }
}


Python




#Python code to find the fields using ID 
#Submit button will be tracked using the CSS Selector
  
from selenium import webdriver
from selenium.webdriver.common.alert import Alert
  
from selenium.webdriver.common.by import By
  
# Initialize a web driver (you may need to download and specify the driver for your browser)
driver = webdriver.Chrome()
try:
    # Open the webpage with the form
    driver.get("http://127.0.0.1:5500/index.html")
  
    # Fill in the form fields
    driver.find_element(by=By.ID, value="FirstName").send_keys("John")
    driver.find_element(by=By.ID, value="DOB").send_keys("19-01-2001")
    driver.find_element(by=By.ID, value="Email").send_keys("john@.com")
    driver.find_element(by=By.ID, value="inputNumber").send_keys("123456789")
    driver.find_element(by=By.ID, value="Male").click()
  
    # Submit the form
    driver.find_element(By.CSS_SELECTOR, "button[type='submit']").click()
  
    alert = Alert(driver)
    alert_text = alert.text
  
    # Check if the alert is open
    if alert_text:
        print("Alert is open, and the content is:", alert_text)
        # You can accept the alert if needed: alert.accept()
    else:
        print("No alert found")
except Exception:
    print("Exception Occurs")
  
input()
# Close the browser
driver.quit()


C#




/*C# code to find the fields using ID 
#Submit button will be tracked using the CSS Selector */
  
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
  
namespace C__Application
{
    internal class Program
    {
        /*
         * Install Dependencies before executing the program
         * dotnet add package Selenium.WebDriver --version 4.15.0
         * dotnet add package Selenium.Support --version 4.1.0
         * dotnet add package Selenium.WebDriver.ChromeDriver --version 99.0.4844.5100
         */
        static void Main(string[] args)
        {
            IWebDriver driver = new ChromeDriver();
  
            driver.Navigate().GoToUrl("http://127.0.0.1:5500/index.html");
            try
            {
                driver.FindElement(By.Id("FirstName")).SendKeys("ram");
                driver.FindElement(By.Id("DOB")).SendKeys("19-01-2001");
                driver.FindElement(By.Id("Email")).SendKeys("ram@gmail.com");
                driver.FindElement(By.Id("inputNumber")).SendKeys("1234566890");
                driver.FindElement(By.Id("Male")).Click();
  
                driver.FindElement(By.CssSelector("button[type='submit']")).Click();
  
                IAlert alert = driver.SwitchTo().Alert();
                string alertText = alert.Text;
  
                // Check if the alert is open
                if (!string.IsNullOrEmpty(alertText))
                {
                    Console.WriteLine("Alert is open, and the content is: \n" + alertText);
                    // You can accept the alert if needed: alert.Accept();
                }
                else
                {
                    Console.WriteLine("No alert found");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.ReadLine();
            driver.Quit();
        }
    }
}


Output:

Below is the output of the code in which the Chrome browser loads and is redirected to the form. And quickly fills in the details and submits the form. We can see that the alert box opens up and the details are shown in the console window.

Output

Result of the Code

Conclusion

This is a simple example but you can now create a complex selenium script with this reference, also you can use the different functions mentioned above. Also, you can write the code for testing the whole website’s behavior on different interactions a user can do.



Similar Reads

submit() element method - Selenium Python
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout - Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What
2 min read
How to add Buttons without Submit the Form in Angular ?
In Angular, when adding buttons to a form, their default behavior on click is to submit the form itself. However, there are certain situations in which it is necessary to create buttons for forms that provide some sort of functionality or trigger custom logic without triggering the default form submission behavior. Steps to Configure the Angular Ap
5 min read
How to use Selenium and Selenium WebDriver Manager to Login to a Website with Python?
Selenium is an open-source tool that is used for automating the tests carried out on different web browsers. Selenium WebDriver is a web framework that allows executing cross-browsing testing. This article focuses on discussing how to log in to a website with Python using Selenium and Selenium WbDriver Manager. Table of Content What is Selenium?Wha
5 min read
What is the Difference Between Selenium Core Extensions and Selenium IDE Extensions?
Selenium is a popular tool for testing and automating web applications. It has changed over time and has different parts that help users in different ways. The two important parts are Selenium Core (from the past) and Selenium IDE. Both have extensions that add additional features to the tool. This article looks at the differences between Selenium
8 min read
Difference Between Selenium 2.0 and Selenium 3.0
Selenium is a leading device for net utility trying out in terms of software program checking out and automation. Selenium has developed through the years, with foremost improvements and upgrades to be had in variations 2.0 and 3.0. Software program testers must recognize the differences between Selenium 2.0 and 3.0 to successfully make use of the
6 min read
Selenium vs Cypress - Which Framework is better to learn Selenium or Cypress?
This article focuses on discussing the key considerations when choosing between Cypress and Selenium for Automation testing. We'll compare their features, benefits, and limitations, helping one determine which framework aligns best with the testing requirements and objectives. Table of Content What is Selenium?Advantages of SeleniumDisadvantages of
5 min read
What is the main difference between Selenium 1 and Selenium 2?
Selenium is a suite of software widely used in the field of automation and testing, it has been a key player in the field of automation for a long time. This article will deep into Automation and discuss the difference between Selenium version 1 and Selenium version 2, highlighting their differences, advantages, and disadvantages. Whether the user
10 min read
Differences Between Selenium Standalone server and Selenium Client and WebDriver Server
In web application testing, Selenium has emerged as one of the most basic foundations, providing robust mechanisms for automating browsers. Among its suite, two elements stand out, which are: 'Selenium-server-standalone.jar' and 'Selenium Client and WebDriver'. Both 'Selenium-server-standalone.jar' and 'Selenium Client and WebDriver' are very impor
4 min read
How to Handle Static Web Tables using Selenium WebDriver using Java?
Web Tables are used to organize similar types of content on the web page, Web tables are groups of elements that are logically stored in a row and column format. Web table has various HTML tags like., table, th, tr, td. Let's understand these tags a bit more: &lt;table&gt; - It defines a table&lt;th&gt; - It defines a header cell&lt;tr&gt; - It def
3 min read
How to Select Multiple Elements using Actions Class in Selenium using Java?
Selenium is an open-source web automation tool that supports many user actions to perform in the web browser. Automating a web page that has file upload or other functionality which requires selecting multiple elements, to perform the multiple select actions the selenium provides a class called Actions. The Action class provides the method for Keyb
2 min read
three90RightbarBannerImg