RPA / Robocorp

Data: enter / Form fill

Basic form filling

tasks.py
Copied!

from robocorp.tasks import task
from robocorp import browser

@task
def fill_basic_form():
    """Fill out a basic web form with text fields, checkboxes, and radio buttons."""
    # Open the browser and navigate to the form page
    page = browser.goto("https://example.com/form")

    # Fill in text fields
    page.fill("input[name='firstName']", "John")
    page.fill("input[name='lastName']", "Smith")
    page.fill("input[name='email']", "[email protected]")

    # Fill in a text area
    page.fill("textarea[name='comments']", "This is a comment entered by automation.")

    # Check a checkbox
    page.check("input[name='subscribe']")

    # Select a radio button
    page.click("input[name='gender'][value='male']")

    # Select from a dropdown menu
    page.select_option("select[name='country']", "USA")

    # Submit the form
    page.click("button[type='submit']")

    # Wait for the confirmation page to load
    page.wait_for_selector(".confirmation-message")

    # Verify the form was submitted successfully
    success_message = page.locator(".confirmation-message").text_content()
    print(f"Form submission result: {success_message}")

Advanced form filling

tasks.py
Copied!

import os
from robocorp.tasks import task
from robocorp import browser

@task
def fill_advanced_form():
    """Demonstrate advanced form filling techniques including file uploads, date pickers, and sliders."""
    # Open the browser and navigate to the form page
    page = browser.goto("https://example.com/advanced-form")

    # === File Upload ===
    # Prepare the file path
    file_path = os.path.abspath("./documents/sample.pdf")

    # Use the specific file input for uploading
    page.set_input_files("input[type='file']", file_path)

    # === Date Picker ===
    # Method 1: Sometimes you can directly set the input value
    page.fill("input[name='appointment-date']", "2023-12-31")

    # Method 2: For more complex date pickers, you might need to interact with the calendar UI
    page.click("input[name='complex-date']")  # Open the date picker
    # Navigate to the correct month (click next month button twice)
    page.click(".date-picker-next-month", click_count=2)
    # Click on day 15
    page.click("text='15'")

    # === Range Slider ===
    # Get the slider element
    slider = page.locator("input[type='range']")

    # Get the bounding box of the slider
    box = slider.bounding_box()

    # Calculate the position for 75% of the slider
    x_position = box["x"] + (box["width"] * 0.75)
    y_position = box["y"] + (box["height"] / 2)

    # Click at the calculated position
    page.mouse.click(x_position, y_position)

    # === Rich Text Editor ===
    # Some rich text editors use iframes or custom elements
    # For a basic contenteditable element:
    page.click("div[contenteditable='true']")
    page.keyboard.type("This is formatted text from automation")

    # === Drag and Drop ===
    # Get the source and target elements
    source = page.locator("#draggable-item")
    target = page.locator("#drop-zone")

    # Perform the drag and drop operation
    source.drag_to(target)

    # === Multiple Select Box ===
    # Select multiple options while holding the Ctrl/Cmd key
    page.select_option("select[multiple]", ["option1", "option3", "option4"])

    # Submit the form
    page.click("button[type='submit']")

    # Wait for confirmation and verify
    page.wait_for_selector(".success-message")
    result = page.locator(".success-message").text_content()
    print(f"Advanced form submission result: {result}")

Form filling with data from Excel

tasks.py
Copied!

import pandas as pd
from robocorp.tasks import task
from robocorp import browser

@task
def fill_forms_from_excel():
    """Fill out multiple forms using data from an Excel spreadsheet."""
    # Load data from Excel file
    excel_path = "data/form_data.xlsx"
    df = pd.read_excel(excel_path)

    # Print summary of data
    print(f"Loaded {len(df)} records from Excel")

    # Initialize the browser
    page = browser.goto("https://example.com/form")

    # Process each row in the Excel file
    for index, row in df.iterrows():
        # Skip if required data is missing
        if pd.isna(row['FirstName']) or pd.isna(row['Email']):
            print(f"Skipping row {index+1} due to missing required data")
            continue

        print(f"Processing record {index+1} of {len(df)}: {row['FirstName']} {row['LastName']}")

        # Fill in the form fields using data from Excel
        page.fill("input[name='firstName']", str(row['FirstName']))
        page.fill("input[name='lastName']", str(row['LastName']) if not pd.isna(row['LastName']) else "")
        page.fill("input[name='email']", str(row['Email']))

        # Handle phone number (if available)
        if not pd.isna(row['Phone']):
            page.fill("input[name='phone']", str(row['Phone']))

        # Handle different countries with appropriate selection
        if not pd.isna(row['Country']):
            page.select_option("select[name='country']", str(row['Country']))

        # Handle subscription preference
        if not pd.isna(row['Subscribe']) and row['Subscribe'] == True:
            page.check("input[name='subscribe']")
        else:
            page.uncheck("input[name='subscribe']")

        # Submit the form
        page.click("button[type='submit']")

        # Wait for confirmation and capture result
        page.wait_for_selector(".confirmation-message")
        result = page.locator(".confirmation-message").text_content()
        print(f"Form {index+1} submission result: {result}")

        # Go back to the form for the next record (if not the last one)
        if index < len(df) - 1:
            page.click("a.back-to-form")
            # Wait for the form to load again
            page.wait_for_selector("input[name='firstName']")

    print("All forms submitted successfully")