Python Script Step
Run custom Python code. Browser control with the Browser Commands library, file operations, API calls, and complex data processing.
What is Python Script?
Python Script Step allows you to run custom Python code within your test flow. With SmartestQA's browser and params objects, you can control the browser and transfer data between parameters.
Browser Control
Click, type, scroll, wait
Parameter Transfer
params.get / set
Custom Logic
Files, API, calculations
Python Script Editor
Syntax highlighting with Monaco editor
Browser Commands Library
Control the browser with SmartestQA's browser object. All commands and their parameters are listed below.
Click Commands
browser.click(selector)
void
Performs a single click on the element.
browser.click("//button[@id='submit']")
browser.click("#login-btn") # CSS selector
browser.double_click(selector)
void
Performs a double click on the element.
browser.double_click("//tr[@class='row']")
browser.right_click(selector)
void
Performs a right click on the element (opens context menu).
browser.right_click("//div[@class='item']")
browser.hover(selector)
void
Moves the mouse over the element (hover effect).
browser.hover("//div[@class='dropdown']")
Input Commands
browser.type(selector, text)
void
Types text into the input field.
browser.type("//input[@name='email']", "test@example.com")
browser.type("#password", "secret123")
browser.clear(selector)
void
Clears the input field.
browser.clear("//input[@id='search']")
browser.select_option(selector, value)
void
Selects from a dropdown (by value or visible text).
browser.select_option("//select[@id='country']", "US")
browser.select_option("#city", "New York")
browser.upload_file(selector, filepath)
void
Uploads a file to the file input.
browser.upload_file("//input[@type='file']", "/path/to/document.pdf")
browser.press_key(key)
void
Presses a keyboard key (Enter, Tab, Escape, etc.).
browser.press_key("Enter")
browser.press_key("Tab")
browser.press_key("Escape")
Get Commands (Retrieving Values)
browser.get_text(selector)
string
Returns the text content of the element.
title = browser.get_text("//h1")
price = browser.get_text("//span[@class='price']")
browser.get_value(selector)
string
Returns the value of the input field.
email = browser.get_value("//input[@name='email']")
browser.get_attribute(selector, attribute)
string
Returns the specified attribute value of the element.
href = browser.get_attribute("//a", "href")
src = browser.get_attribute("//img", "src")
data_id = browser.get_attribute("//div", "data-id")
browser.get_url()
string
Returns the URL of the current page.
current_url = browser.get_url()
browser.get_title()
string
Returns the page title.
page_title = browser.get_title()
browser.is_visible(selector)
boolean
Returns whether the element is visible.
if browser.is_visible("//div[@class='error']"):
print("Error message is displayed")
browser.is_enabled(selector)
boolean
Returns whether the element is enabled.
if browser.is_enabled("//button[@id='submit']"):
browser.click("//button[@id='submit']")
browser.get_element_count(selector)
int
Returns the number of elements matching the selector.
row_count = browser.get_element_count("//table//tr")
print(f"Table has {row_count} rows")
Wait Commands
browser.wait_for_element(selector, timeout=10)
void
Waits until the element is present in the DOM.
browser.wait_for_element("//div[@class='loaded']")
browser.wait_for_element("//table", timeout=30)
browser.wait_for_visible(selector, timeout=10)
void
Waits until the element is visible.
browser.wait_for_visible("//div[@id='modal']")
browser.wait_for_invisible(selector, timeout=10)
void
Waits until the element disappears (loading spinner, etc.).
browser.wait_for_invisible("//div[@class='spinner']")
browser.wait_for_text(selector, text, timeout=10)
void
Waits until the element contains the specified text.
browser.wait_for_text("//span[@id='status']", "Completed")
browser.sleep(seconds)
void
Waits for the specified duration (hard wait - not recommended).
browser.sleep(2) # Wait 2 seconds
Frame & Window Commands
browser.switch_to_frame(selector)
void
Switches to the specified iframe.
browser.switch_to_frame("//iframe[@id='payment']")
browser.switch_to_default()
void
Returns to the main page (default content).
browser.switch_to_default()
browser.switch_to_window(handle)
void
Switches to the specified window.
handles = browser.get_window_handles()
browser.switch_to_window(handles[1]) # Second window
browser.get_window_handles()
list
Returns a list of handles for all open windows.
handles = browser.get_window_handles()
print(f"{len(handles)} windows are open")
browser.close_window()
void
Closes the current window.
browser.close_window()
Alert Commands
browser.accept_alert()
void
Accepts the JavaScript alert/confirm (OK).
browser.accept_alert()
browser.dismiss_alert()
void
Dismisses the JavaScript alert/confirm (Cancel).
browser.dismiss_alert()
browser.get_alert_text()
string
Returns the alert message.
message = browser.get_alert_text()
print(f"Alert: {message}")
browser.send_alert_text(text)
void
Enters text into a prompt alert.
browser.send_alert_text("Confirmation code")
Other Commands
browser.screenshot(filename)
void
Takes a screenshot and saves it.
browser.screenshot("login_success.png")
browser.execute_js(script)
any
Executes JavaScript code and returns the result.
title = browser.execute_js("return document.title")
browser.execute_js("window.scrollTo(0, document.body.scrollHeight)")
storage = browser.execute_js("return localStorage.getItem('token')")
browser.set_window_size(width, height)
void
Sets the browser window size.
browser.set_window_size(1920, 1080) # Full HD
browser.set_window_size(375, 812) # iPhone X
browser.maximize_window()
void
Maximizes the window.
browser.maximize_window()
Params Object (Parameter Management)
Use the params object to read and write test parameters. Used for data transfer between steps.
params.get(key)
string | None
Returns the value of a global parameter.
username = params.get("username")
base_url = params.get("base_url")
params.set(key, value)
void
Sets a parameter value (can be used in subsequent steps).
order_id = browser.get_text("//span[@class='order-id']")
params.set("order_id", order_id)
# Use in subsequent steps
# With {{order_id}} format or params.get("order_id")
params.get_all()
dict
Returns all parameters as a dictionary.
all_params = params.get_all()
for key, value in all_params.items():
print(f"{key}: {value}")
Example Code
Login Process
# Get user credentials from parameters
username = params.get("username")
password = params.get("password")
# Fill in the login form
browser.type("//input[@id='email']", username)
browser.type("//input[@id='password']", password)
browser.click("//button[@type='submit']")
# Wait for dashboard to load
browser.wait_for_element("//div[@class='dashboard']", timeout=15)
# Check for successful login
if browser.is_visible("//span[@class='user-name']"):
params.set("login_status", "success")
else:
params.set("login_status", "failed")
Extracting Table Data
# Count all rows in the table
row_count = browser.get_element_count("//table[@id='orders']//tbody//tr")
params.set("total_orders", str(row_count))
# Get the order ID from the first row
first_order = browser.get_text("//table[@id='orders']//tbody//tr[1]//td[1]")
params.set("first_order_id", first_order)
# Get total amount and convert to number
total_text = browser.get_text("//span[@class='total-amount']")
total = float(total_text.replace("$", "").replace(",", "").strip())
params.set("total_amount", str(total))
Reading Data from JSON File
import json
# Read test data
with open("test_data/users.json", "r", encoding="utf-8") as f:
users = json.load(f)
# Get the first user
user = users[0]
browser.type("//input[@name='name']", user["name"])
browser.type("//input[@name='email']", user["email"])
browser.type("//input[@name='phone']", user["phone"])
Generating Dynamic Data
import random
import string
from datetime import datetime
# Generate random email
random_str = ''.join(random.choices(string.ascii_lowercase, k=8))
email = f"test_{random_str}@example.com"
params.set("generated_email", email)
# Get today's date
today = datetime.now().strftime("%m/%d/%Y")
params.set("current_date", today)
# Generate random phone number
phone = "555" + ''.join(random.choices(string.digits, k=7))
params.set("generated_phone", phone)
New Window Operations
# Save the current window
main_window = browser.get_window_handles()[0]
# Click link that opens a new window
browser.click("//a[@target='_blank']")
browser.sleep(1)
# Switch to the new window
handles = browser.get_window_handles()
browser.switch_to_window(handles[1])
# Perform operations
new_page_title = browser.get_title()
params.set("new_page_title", new_page_title)
# Close the new window and return to main window
browser.close_window()
browser.switch_to_window(main_window)
Frequently Asked Questions
Which Python libraries can be used?
Standard Python libraries (json, os, re, datetime, random, string, etc.) and SmartestQA's browser / params objects can be used. For additional libraries (requests, pandas, etc.), pip installation on the agent is required.
What Python version is used?
SmartestQA agents use Python 3.9+. Modern Python features like f-strings, type hints, and walrus operator are supported.
How do I debug?
You can log to the console using print(). Logs appear in the test report and Dry Run screen. You can also take instant screenshots with browser.screenshot("debug.png").
What is the difference between Python Script and JavaScript?
Python Script runs on the agent side, can perform file operations, and connect to external APIs. JavaScript runs inside the browser and is ideal for DOM manipulation and localStorage access.