"""
Web Form Automation Script using Selenium
=========================================
This script automates data entry into web forms. It uses Selenium WebDriver to control a browser,
navigate to a given URL, fill form fields based on CSS selectors or XPath, and optionally submit the form.
Requirements:
- Python 3.6+
- Install dependencies: pip install selenium webdriver-manager
Usage:
1. Update the `form_data` dictionary with your form fields (selector: value pairs).
- Selectors can be CSS selectors (e.g., '#email') or XPath (e.g., 'xpath://input[@name="email"]').
2. Set the target URL.
3. Run the script: python form_automator.py
Safety Notes:
- Use responsibly (e.g., for testing your own sites or with permission).
- Some sites detect automation; use headless mode or proxies if needed.
- Handle CAPTCHA or 2FA manually if encountered.
"""
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.chrome.options import Options
import time
def automate_form(url, form_data, submit_selector=None, headless=False, wait_time=10):
"""
Automates filling a web form.
Args:
- url (str): Target webpage URL.
- form_data (dict): {selector: value} where selector is CSS or XPath.
- submit_selector (str, optional): Selector for submit button.
- headless (bool): Run browser in headless mode.
- wait_time (int): Max wait time for elements (seconds).
"""
# Setup Chrome options
chrome_options = Options()
if headless:
chrome_options.add_argument("--headless")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument("--disable-dev-shm-usage")
# Initialize driver
service = Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
try:
# Navigate to URL
driver.get(url)
print(f"Navigated to: {url}")
wait = WebDriverWait(driver, wait_time)
# Fill each form field
for selector, value in form_data.items():
by_type = By.CSS_SELECTOR if not selector.startswith('xpath:') else By.XPATH
if selector.startswith('xpath:'):
selector = selector[6:] # Strip 'xpath:' prefix
element = wait.until(EC.presence_of_element_located((by_type, selector)))
element.clear()
element.send_keys(str(value))
print(f"Filled '{selector}': {value}")
# Submit form if selector provided
if submit_selector:
by_type = By.CSS_SELECTOR if not submit_selector.startswith('xpath:') else By.XPATH
if submit_selector.startswith('xpath:'):
submit_selector = submit_selector[6:]
submit_btn = wait.until(EC.element_to_be_clickable((by_type, submit_selector)))
submit_btn.click()
print("Form submitted!")
time.sleep(3) # Brief pause to see result
print("Automation complete!")
input("Press Enter to close browser...") # Pause to inspect
except Exception as e:
print(f"Error: {e}")
finally:
driver.quit()
# Example Usage
if __name__ == "__main__":
# Example: Automate a demo form (replace with real URL)
TARGET_URL = "https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_submit" # Demo form
FORM_DATA = {
'input[name="fname"]': 'John', # CSS selector for first name
'input[name="lname"]': 'Doe', # CSS selector for last name
'xpath://input[@name="email"]': 'john@example.com', # XPath example
}
SUBMIT_SELECTOR = 'input[type="submit"]' # Submit button
# Run automation (set headless=True to run without UI)
automate_form(TARGET_URL, FORM_DATA, SUBMIT_SELECTOR, headless=False)
Quick Start Guide
-
Install Dependencies:
pip install selenium webdriver-manager
-
Customize:
- Change
TARGET_URL to your form's URL.
- Update
FORM_DATA with real selectors (use browser DevTools to find them: right-click element > Inspect > Copy selector/XPath).
- Add
SUBMIT_SELECTOR if needed.
-
Run:
python form_automator.py
Tips for Real-World Use
- Selectors: Prefer CSS for speed; use XPath for complex cases. Prefix XPath with
xpath:.
- Dynamic Forms: Increase
wait_time or add EC.visibility_of_element_located.
- Headless Mode: Set
headless=True for servers/background runs.
- Multiple Pages/Frames: Add
driver.switch_to.frame() if needed.
- Errors: Common issues – stale elements (retry logic), anti-bot detection (use undetected-chromedriver library).
- Advanced: Integrate with Pandas for bulk data from CSV/Excel.
This script is modular and extensible. Let me know if you need tweaks! 🕵️