How to Handle Input Forms in Selenium

How to Handle Input Forms in Selenium

Handling input forms in Selenium involves several steps including locating the input elements, entering data into them, and submitting the form. Below is a step-by-step guide using Python with Selenium:

✅ Prerequisites

Install Selenium:

bash

Copy

Edit

pip install selenium

Download WebDriver:

Choose the appropriate WebDriver (e.g., ChromeDriver, GeckoDriver) and make sure it's in your system path.


πŸ”Ή Example: Filling and Submitting a Form

Let's say we have a simple HTML form like this:


html

Copy

Edit

<form id="loginForm">

  <input type="text" name="username" id="username">

  <input type="password" name="password" id="password">

  <button type="submit">Login</button>

</form>

πŸ§ͺ Selenium Code to Handle the Form

python

Copy

Edit

from selenium import webdriver

from selenium.webdriver.common.by import By

from selenium.webdriver.common.keys import Keys

import time


# Initialize the WebDriver

driver = webdriver.Chrome()


# Open the web page

driver.get("https://example.com/login")  # Replace with your URL


# Locate form fields and input data

username_input = driver.find_element(By.ID, "username")

password_input = driver.find_element(By.ID, "password")


username_input.send_keys("myUsername")

password_input.send_keys("myPassword")


# Submit the form (by clicking button)

login_button = driver.find_element(By.XPATH, "//button[@type='submit']")

login_button.click()


# Wait for a few seconds to see the result

time.sleep(5)


# Close the browser

driver.quit()

πŸ›  Tips

Use By.ID, By.NAME, By.XPATH, or By.CSS_SELECTOR to locate form fields.


Use send_keys() to simulate typing into input fields.


Use click() to press buttons.


To submit forms directly, you can also use:


python

Copy

Edit

password_input.send_keys(Keys.RETURN)

πŸ“Œ Advanced Options

Wait for elements to load:

Use WebDriverWait and expected_conditions to handle dynamic loading.


python

Copy

Edit

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC


WebDriverWait(driver, 10).until(

    EC.presence_of_element_located((By.ID, "username"))

)

Handle dropdowns:

Use the Select class from selenium.webdriver.support.ui.


Would you like an example for a more complex form (e.g., radio buttons, checkboxes, dropdowns)?

Learn Selenium JAVA Course in Hyderabad

Read More

Working with ChromeDriver, GeckoDriver, and EdgeDriver

Difference Between Selenium RC, IDE, and WebDriver

Visit Our IHUB Talent Training in Hyderabad

Get Directions

Comments

Popular posts from this blog

How to Install and Set Up Selenium in Python (Step-by-Step)

Feeling Stuck in Manual Testing? Here’s Why You Should Learn Automation Testing

A Beginner's Guide to ETL Testing: What You Need to Know