Build your own AI Operator in python – OpenAI -API – Step-by-Step Guide

 

 

Python AI Web Automation – Step-by-Step Guide

Introduction

This Python script automates web interactions using AI and Selenium. It extracts webpage elements, sends them to OpenAI for analysis, and executes suggested actions.

Requirements

Ensure you have the following installed:

  • Thonny (Beginner-friendly Python IDE)
  • Python 3.8 or newer
  • Required Python packages:

Installing Required Packages

Open Thonny and install the necessary dependencies. Click on Tools → Manage Packages and install the following:

pip install selenium webdriver-manager openai beautifulsoup4

How to Use

  1. Open Thonny.
  2. Copy and paste the script below into a new file.
  3. Run the script by clicking the Run button.
  4. Enter your OpenAI API key, the target URL, and the task description.
  5. Click “Start AI Automation” and review the AI-suggested actions.
  6. Confirm and execute the automated process.

Python Script

import tkinter as tk
from tkinter import scrolledtext, messagebox, simpledialog
import threading
import time
import json
# Selenium & Browser Manager imports
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
# OpenAI import
import openai
# BeautifulSoup for DOM parsing
from bs4 import BeautifulSoup
# -------------------- GUI Setup --------------------
root = tk.Tk()
root.title("AI Web Automation")
root.geometry("800x600")
# Frame for input fields
top_frame = tk.Frame(root)
top_frame.pack(pady=10)
# OpenAI API Key Entry
tk.Label(top_frame, text="Enter OpenAI API Key:").grid(row=0, column=0, sticky='w')
api_key_entry = tk.Entry(top_frame, width=40, show="*")
api_key_entry.grid(row=0, column=1, padx=5, pady=5)
# Task Entry Field
tk.Label(top_frame, text="Task:").grid(row=1, column=0, sticky='w')
task_entry = tk.Entry(top_frame, width=40)
task_entry.grid(row=1, column=1, padx=5, pady=5)
# URL Entry Field
tk.Label(top_frame, text="Website URL:").grid(row=2, column=0, sticky='w')
url_entry = tk.Entry(top_frame, width=40)
url_entry.insert(0, "https://www.yourwebsite.com")  # Change the default URL as needed
url_entry.grid(row=2, column=1, padx=5, pady=5)
# Headless Mode Checkbox
headless_var = tk.BooleanVar(value=True)
headless_checkbox = tk.Checkbutton(top_frame, text="Run in headless mode", variable=headless_var)
headless_checkbox.grid(row=3, column=1, sticky='w', padx=5, pady=5)
# -------------------- Log & Status Widgets --------------------
tk.Label(root, text="Output Log:").pack()
output_text = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=90, height=20)
output_text.pack(pady=5)
status_label = tk.Label(root, text="Status: Idle", anchor="w")
status_label.pack(fill=tk.X, padx=5, pady=5)
def log_message(message):
    """Logs messages to the GUI text output with a timestamp."""
    timestamp = time.strftime("[%Y-%m-%d %H:%M:%S]")
    output_text.insert(tk.END, f"{timestamp} {message}\n")
    output_text.see(tk.END)
    root.update()
def update_status(message):
    """Updates the status label."""
    status_label.config(text=f"Status: {message}")
    root.update()
def clear_log():
    """Clears the output log."""
    output_text.delete(1.0, tk.END)
clear_log_button = tk.Button(root, text="Clear Log", command=clear_log)
clear_log_button.pack(pady=5)
# -------------------- Core Automation Functions --------------------
def extract_dom(driver):
    """
    Extracts interactive elements from the webpage using BeautifulSoup.
    This avoids stale element references by using the page source.
    """
    log_message("Extracting webpage structure using BeautifulSoup...")
    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")
    
    # Find all interactive tags (including textarea and select)
    interactive_tags = soup.find_all(["input", "button", "form", "a", "textarea", "select"])
    extracted_data = []
    for tag in interactive_tags:
        tag_name = tag.name
        attributes = {}
        for attr in ["id", "name", "class", "placeholder", "type", "href", "onclick"]:
            if tag.has_attr(attr):
                attributes[attr] = tag[attr]
        text = tag.get_text(strip=True)
        extracted_data.append({"tag": tag_name, "text": text, "attributes": attributes})
    
    log_message(f"Extracted {len(extracted_data)} interactive elements.")
    return json.dumps(extracted_data, indent=2)
def analyze_with_ai(dom_text, task, api_key):
    """
    Sends the extracted DOM and task to OpenAI for analysis.
    The prompt instructs the AI to provide a JSON list of actions only.
    """
    log_message("Sending webpage structure to AI for analysis...")
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4-turbo",
            api_key=api_key,
            messages=[
                {"role": "system", "content": (
                    "Analyze this webpage and suggest actions. Provide only a JSON list of actions, with no additional commentary. "
                    "Each action should be a JSON object with keys: 'action', 'method', 'selector', 'value' (if applicable), and 'description'."
                )},
                {"role": "user", "content": f"Task: {task}\n\nWebpage Structure:\n{dom_text}"}
            ]
        )
        ai_response = response["choices"][0]["message"]["content"].strip()
        log_message("AI analysis complete.")
        return ai_response
    except Exception as e:
        log_message(f"AI Error: {str(e)}")
        return None
def user_confirmation(message):
    """Prompts the user for confirmation before proceeding."""
    return messagebox.askyesno("Confirmation", message)
def execute_actions(actions, driver):
    """
    Parses and executes the AI-driven automation steps using live Selenium commands.
    Expected JSON action structure:
       {
         "action": e.g., "click", "fill", "scroll", "select",
         "method": e.g., "xpath", "css", "name", "id" (or synonyms such as "selector_id", "setvalue", etc.),
         "selector": "the locator string",
         "value": "value to enter or option to select (if applicable)",
         "description": "Human-readable description"
       }
    If a dropdown (select) action fails, the user is prompted for the correct option.
    """
    log_message("Executing AI-driven automation steps...")
    try:
        parsed_actions = json.loads(actions)
    except json.JSONDecodeError as e:
        log_message(f"JSON Decode Error: {e}")
        messagebox.showerror("JSON Error", f"Actions could not be parsed as JSON:\n{e}\n\nRaw response:\n{actions}")
        return
    # Mapping for common synonyms to proper locator methods.
    method_mapping = {
        "selector_id": "id",
        "selector_name": "name",
        "setvalue": "name",
        "inserttext": "name",
        "selectoption": "name"
    }
    # Use an explicit wait for element presence.
    wait = WebDriverWait(driver, 10)
    for idx, action in enumerate(parsed_actions):
        description = action.get("description", f"Step {idx+1}")
        raw_action_type = action.get("action", "").lower()
        # Deduce the action type if not one of our expected ones.
        if raw_action_type not in ["click", "fill", "scroll", "select"]:
            lower_desc = description.lower()
            if "enter" in lower_desc or "fill" in lower_desc:
                action_type = "fill"
            elif "click" in lower_desc or "submit" in lower_desc:
                action_type = "click"
            elif "select" in lower_desc:
                action_type = "select"
            else:
                log_message(f"Unable to deduce action type for step: {description}. Skipping.")
                continue
        else:
            action_type = raw_action_type
        # Process the locator method.
        method = action.get("method", "").lower()
        selector = action.get("selector", "")
        value = action.get("value", "")
        # Remap synonyms if needed.
        if method in method_mapping:
            locator_method = method_mapping[method]
            log_message(f"Mapping method '{method}' to '{locator_method}'.")
        elif method in ["xpath", "css", "name", "id"]:
            locator_method = method
        else:
            # If unknown, deduce based on selector.
            if selector.lower().startswith("select"):
                locator_method = "css"
            elif selector.startswith("/"):
                locator_method = "xpath"
            elif selector.startswith("#") or selector.startswith("."):
                locator_method = "css"
            else:
                locator_method = "name"
            log_message(f"Method '{method}' is not recognized; deduced locator method as '{locator_method}' based on selector '{selector}'.")
        # Special handling for the address field:
        # If this is a fill action for the address and the description mentions "address"
        # and if the selector appears to target an input (but our form uses a textarea),
        # adjust the XPath if needed.
        if action_type == "fill" and "address" in description.lower() and locator_method == "xpath":
            if "input" in selector:
                new_selector = selector.replace("input", "textarea", 1)
                log_message(f"Adjusted XPath selector for address field: '{selector}' -> '{new_selector}'")
                selector = new_selector
        # Special handling for the submit button:
        # If this is a click action for submit, force using element_to_be_clickable.
        if action_type == "click" and ("submit" in description.lower() or "lead_link_submit" in selector.lower()):
            # Force locator method to CSS if the selector looks like a CSS selector.
            if not locator_method == "css" and selector.startswith("input["):
                locator_method = "css"
                log_message(f"Forcing locator method to 'css' for submit button based on selector '{selector}'.")
        log_message(f"Executing: {description} using locator method '{locator_method}' and selector '{selector}'")
        try:
            # Locate the element.
            if action_type == "click":
                # For click actions, wait until the element is clickable.
                if locator_method == "xpath":
                    element = wait.until(EC.element_to_be_clickable((By.XPATH, selector)))
                elif locator_method == "css":
                    element = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, selector)))
                elif locator_method == "name":
                    element = wait.until(EC.element_to_be_clickable((By.NAME, selector)))
                elif locator_method == "id":
                    element = wait.until(EC.element_to_be_clickable((By.ID, selector)))
                else:
                    log_message(f"Cannot locate element: unknown locator method '{locator_method}'")
                    continue
            else:
                # For other actions, wait for presence.
                if locator_method == "xpath":
                    element = wait.until(EC.presence_of_element_located((By.XPATH, selector)))
                elif locator_method == "css":
                    element = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, selector)))
                elif locator_method == "name":
                    element = wait.until(EC.presence_of_element_located((By.NAME, selector)))
                elif locator_method == "id":
                    element = wait.until(EC.presence_of_element_located((By.ID, selector)))
                else:
                    log_message(f"Cannot locate element: unknown locator method '{locator_method}'")
                    continue
            # For click actions, scroll the element into view and then click.
            if action_type == "click":
                driver.execute_script("arguments[0].scrollIntoView(true);", element)
                element.click()
            elif action_type == "fill":
                element.clear()
                element.send_keys(value)
            elif action_type == "scroll":
                driver.execute_script("arguments[0].scrollIntoView();", element)
            elif action_type == "select":
                try:
                    select_obj = Select(element)
                    select_obj.select_by_visible_text(value)
                except Exception as inner_e:
                    log_message(f"Error during '{description}': {inner_e}")
                    # Prompt the user for input if dropdown selection fails.
                    new_value = simpledialog.askstring("Dropdown Issue",
                        f"Error encountered while selecting option for '{description}'.\n"
                        f"Please enter the correct visible text option (attempted: '{value}'):")
                    if new_value:
                        try:
                            select_obj.select_by_visible_text(new_value)
                        except Exception as e:
                            log_message(f"Failed after user input for '{description}': {e}")
                    else:
                        log_message(f"No input provided for dropdown selection for '{description}'. Skipping.")
            else:
                log_message(f"Unsupported action type: {action_type}")
            time.sleep(1)  # Delay between actions for stability.
        except Exception as inner_e:
            log_message(f"Error during '{description}': {inner_e}")
    log_message("All actions executed successfully.")
def perform_task():
    """Main function that drives the automation process. Runs in its own thread."""
    api_key = api_key_entry.get().strip()
    task = task_entry.get().strip()
    url = url_entry.get().strip()
    headless = headless_var.get()
    if not api_key or not task or not url:
        messagebox.showwarning("Input Error", "Please ensure API key, task, and URL are all provided.")
        return
    update_status("Initializing browser...")
    log_message("Initializing browser...")
    # Setup Selenium WebDriver with options.
    options = Options()
    if headless:
        options.add_argument("--headless")
    try:
        driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)
    except Exception as e:
        log_message(f"Browser initialization error: {str(e)}")
        update_status("Error initializing browser")
        return
    try:
        log_message(f"Opening website: {url}")
        driver.get(url)
        time.sleep(3)  # Allow page to load.
    except Exception as e:
        log_message(f"Error opening website: {str(e)}")
        driver.quit()
        update_status("Error opening website")
        return
    # Step 1: Extract the DOM structure using BeautifulSoup.
    dom_text = extract_dom(driver)
    # Step 2: AI Analysis of the DOM.
    ai_actions = analyze_with_ai(dom_text, task, api_key)
    if not ai_actions:
        log_message("AI failed to generate actions. Exiting.")
        driver.quit()
        update_status("Idle")
        return
    # Step 3: Display AI Suggested Actions for Review & Editing.
    action_window = tk.Toplevel(root)
    action_window.title("Review AI Actions")
    action_window.geometry("600x400")
    tk.Label(action_window, text="AI Suggested Actions (edit if necessary):").pack(pady=5)
    action_text = scrolledtext.ScrolledText(action_window, wrap=tk.WORD, width=70, height=20)
    action_text.pack(pady=5)
    action_text.insert(tk.END, ai_actions)
    def confirm_and_execute():
        edited_actions = action_text.get("1.0", tk.END).strip()
        if not edited_actions:
            log_message("No actions provided. Aborting execution.")
            action_window.destroy()
            driver.quit()
            update_status("Idle")
            return
        action_window.destroy()
        if user_confirmation("Do you want to proceed with these AI actions?"):
            log_message("Executing AI-driven automation...")
            execute_actions(edited_actions, driver)
        else:
            log_message("Task aborted by user.")
        driver.quit()
        log_message("Browser closed.")
        update_status("Idle")
    confirm_button = tk.Button(action_window, text="Confirm and Execute", command=confirm_and_execute)
    confirm_button.pack(pady=10)
    update_status("Awaiting user confirmation...")
def start_task_thread():
    """Starts the perform_task function in a separate thread to keep the GUI responsive."""
    task_thread = threading.Thread(target=perform_task)
    task_thread.start()
# -------------------- Execute Button --------------------
execute_button = tk.Button(root, text="Start AI Automation", command=start_task_thread)
execute_button.pack(pady=10)
# -------------------- Run Tkinter GUI --------------------
root.mainloop()

    

Troubleshooting

If you encounter issues, try the following:

  • Ensure Chrome is installed and updated.
  • Run pip install --upgrade selenium webdriver-manager openai beautifulsoup4.
  • Check if the OpenAI API key is valid.
  • Ensure the entered URL is accessible.

Conclusion

This script leverages AI and Selenium to automate web tasks dynamically. It provides a user-friendly GUI for input, logs actions, and executes automation with AI-driven intelligence.