Helper functions and reusable code for Selenium automation.
Utility scripts provide:
- Browser initialization and cleanup
- Element finding and interaction helpers
- Wait helper functions
- Configuration management
- Logging utilities
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)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 Nonedef 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 Falsedef 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 Falseimport 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- 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
Use descriptive names:
*_utils.pyfor utility functions*_helpers.pyfor helper functionsconfig.pyfor configuration