Skip to main content

A Python library for managing Selenium Chrome connections.

Project description

Selenium Chrome Pool

A Python library for managing Selenium Chrome connections, designed to prevent excessive page loads causing crashes and provide connection pool management.

Features

  • Connection Pool Management: Limits the maximum number of Chrome instances to prevent excessive resource usage.
  • Idle Connection Cleanup: Automatically closes connections that have been idle for a long time, releasing resources.
  • Thread-Safe: Supports concurrent access from multiple threads.
  • Headless Mode: Supports running Chrome in headless mode.
  • Remote WebDriver: Supports connecting to a remote Selenium Grid or standalone-chrome container.
  • Automatic Cleanup: Automatically closes all connections when the program exits.

Installation

pip install selenium_chrome_pool  # (If published to PyPI)
# Or, for local installation:
pip install .

Prerequisites

Selenium is installed: pip install selenium
Chrome WebDriver (ChromeDriver) is installed. Ensure the ChromeDriver version is compatible with your Chrome browser version and add it to your PATH environment variable, or specify its path when using SeleniumChromePool. (ChromeDriver is not required if using a remote WebDriver)

Usage

from selenium_chrome_pool import SeleniumChromePool
import threading
import time

# 1. Create a connection pool
# remote_url = "http://192.168.1.100:4444/wd/hub"  # Remote Selenium Grid address (optional)
remote_url = None  # Use local chromedriver
pool = SeleniumChromePool(max_connections=3, headless=True, remote_url=remote_url)
pool.start_cleanup_thread()  # Start the cleanup thread (must be called)

# 2. Get a connection from the pool
def worker(task_id):
    driver = pool.get_connection()
    if driver:
        try:
            driver.get("https://www.baidu.com")
            print(f"Task {task_id}: Page title: {driver.title}")
            time.sleep(5)  # Simulate task execution time
        except Exception as e:
            print(f"Task {task_id}: Error: {e}")
        finally:
            # 3. Release the connection
            pool.release_connection(driver)
    else:
        print(f"Task {task_id}: Failed to get connection.")


# Simulate multiple concurrent tasks
threads = []
for i in range(5):  # Simulate 5 concurrent tasks
    t = threading.Thread(target=worker, args=(i,))
    threads.append(t)
    t.start()

for t in threads:
    t.join()

time.sleep(5)  # Wait for a while to observe if the cleanup thread works
# pool.close_all_connections()  # No need to call manually, atexit will handle it

print("Program finished")

Important Notes:

  • Make sure to call start_cleanup_thread() before using SeleniumChromePool to start the idle connection cleanup thread. This is crucial for proper resource management.
  • Call release_connection() after using the connection to return it to the pool.
  • You don't need to manually call close_all_connections() when the program exits. The atexit module will automatically close all connections.

Parameter Descriptions

  • max_connections: The maximum number of connections in the pool (default: 5).
  • max_idle_time: The maximum idle time for a connection in seconds (default: 300). Connections that have been idle for longer than this time will be cleaned up.
  • headless: Whether to run Chrome in headless mode (default: True).
  • chrome_options: A selenium.webdriver.chrome.options.Options instance for configuring Chrome options (optional).
  • remote_url: The remote URL of the Selenium Grid or standalone-chrome (optional). If not provided, the local ChromeDriver will be used. Example: "http://192.168.1.100:4444/wd/hub"

Error Handling

If a connection cannot be retrieved from the pool, the get_connection() method will return None. Make sure to check if the connection is valid before using it.

Contributing

Feel free to submit issues and pull requests!

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

selenium_chrome_pool-0.1.3.tar.gz (5.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

selenium_chrome_pool-0.1.3-py3-none-any.whl (6.1 kB view details)

Uploaded Python 3

File details

Details for the file selenium_chrome_pool-0.1.3.tar.gz.

File metadata

  • Download URL: selenium_chrome_pool-0.1.3.tar.gz
  • Upload date:
  • Size: 5.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.11.2

File hashes

Hashes for selenium_chrome_pool-0.1.3.tar.gz
Algorithm Hash digest
SHA256 5ab1b41f1819f8212eb2b67543c5bbe6291a5976cc2f75288b6db32dcb70cc8d
MD5 0614076a1f53feba16e755d6dcaf9810
BLAKE2b-256 88fe5527ba553f035ad88a986df4daf679d94e607df90071b9ddbf9e11954988

See more details on using hashes here.

File details

Details for the file selenium_chrome_pool-0.1.3-py3-none-any.whl.

File metadata

File hashes

Hashes for selenium_chrome_pool-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 b9eaca50f51768c6458d0ffae09d06334be6d66e9b83b10aac545e90cd76d1b5
MD5 f4821ae17fbd786a643a6da65b977872
BLAKE2b-256 be9ee7fe48dfc24afae9261ee754350db827c11ab83c8085447922eaab2547ce

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page