Open In App

How to Submit a Form using Selenium?

Last Updated : 04 Dec, 2023
Improve
Improve
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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads