0
0
Selenium Pythontesting~5 mins

Docker containers for test execution in Selenium Python

Choose your learning style9 modes available
Introduction

Docker containers help run tests in a clean, controlled space. This makes tests reliable and easy to share.

You want to run Selenium tests on different machines without setup problems.
You need to test on a specific browser version without installing it locally.
You want to run tests in the cloud or on a server easily.
You want to keep your computer clean from test tools and browsers.
You want to share your test setup with teammates exactly as it is.
Syntax
Selenium Python
docker run -d -p 4444:4444 selenium/standalone-chrome

# Run your Selenium Python test script connecting to http://localhost:4444/wd/hub

This command starts a Docker container with Chrome and Selenium server ready.

Tests connect to the Selenium server URL inside the container.

Examples
Starts a container with Firefox browser for Selenium tests.
Selenium Python
docker run -d -p 4444:4444 selenium/standalone-firefox
Starts Chrome container with more shared memory to avoid crashes in heavy tests.
Selenium Python
docker run -d -p 4444:4444 --shm-size=2g selenium/standalone-chrome
Mounts your local test folder inside the container for easy access.
Selenium Python
docker run -d -p 4444:4444 -v /my/tests:/tests selenium/standalone-chrome
Sample Program

This Python script connects to the Selenium server running inside the Docker container. It opens example.com, checks the main heading, and prints a success message if the test passes.

Selenium Python
from selenium import webdriver
from selenium.webdriver.common.by import By

# Connect to Selenium server in Docker
options = webdriver.ChromeOptions()
remote_url = 'http://localhost:4444/wd/hub'

# Create remote WebDriver
with webdriver.Remote(command_executor=remote_url, options=options) as driver:
    driver.get('https://example.com')
    heading = driver.find_element(By.TAG_NAME, 'h1').text
    assert heading == 'Example Domain', f'Heading was {heading}'
    print('Test passed: Heading is correct')
OutputSuccess
Important Notes

Make sure Docker is installed and running before starting containers.

Use the correct Selenium image version to match your browser and Selenium client versions.

Expose the container port (usually 4444) to connect your test scripts.

Summary

Docker containers create a clean environment for running Selenium tests.

They help avoid setup issues and make tests portable.

Connect your Selenium Python tests to the container's Selenium server URL.