Skip to content

Latest commit

 

History

History
118 lines (97 loc) · 2.87 KB

File metadata and controls

118 lines (97 loc) · 2.87 KB

Utility Scripts and Functions

Helper functions and reusable code for Selenium automation.

Purpose

Utility scripts provide:

  • Browser initialization and cleanup
  • Element finding and interaction helpers
  • Wait helper functions
  • Configuration management
  • Logging utilities

Scripts

quitBrowser.py

Safe browser cleanup and resource management.

Features:

  • Graceful driver termination
  • Resource cleanup
  • Error handling

Usage:

from quitBrowser import quit_browser

try:
    # Use driver
    driver.get("https://example.com")
finally:
    quit_browser(driver)

Common Utilities

Safe Element Finding

def find_element_safe(driver, by, value, wait_time=10):
    """Find element with explicit wait and error handling."""
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    try:
        element = WebDriverWait(driver, wait_time).until(
            EC.presence_of_element_located((by, value))
        )
        return element
    except Exception as e:
        print(f"Element not found: {e}")
        return None

Safe Clicking

def click_element_safe(driver, by, value):
    """Click element with error handling."""
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    try:
        element = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((by, value))
        )
        element.click()
        return True
    except Exception as e:
        print(f"Click failed: {e}")
        return False

Safe Text Input

def send_keys_safe(driver, by, value, text):
    """Send text to element with error handling."""
    try:
        element = driver.find_element(by, value)
        element.clear()
        element.send_keys(text)
        return True
    except Exception as e:
        print(f"Text input failed: {e}")
        return False

Screenshot on Error

import datetime

def take_screenshot(driver, filename=None):
    """Take screenshot for debugging."""
    if not filename:
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"screenshot_{timestamp}.png"
    
    try:
        driver.save_screenshot(filename)
        print(f"Screenshot saved: {filename}")
        return filename
    except Exception as e:
        print(f"Screenshot failed: {e}")
        return None

Recommended Utilities to Create

  • driver_utils.py: WebDriver initialization and configuration
  • element_utils.py: Element finding and interaction
  • wait_utils.py: Wait condition helpers
  • config.py: Configuration and constants
  • logger_utils.py: Logging setup

File Naming

Use descriptive names:

  • *_utils.py for utility functions
  • *_helpers.py for helper functions
  • config.py for configuration