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
Comments
Post a Comment