How Python Selenium Automation Can Work with DevOps Docker?

Ahson Shaikh
2 min readSep 30, 2023

--

Selenium Grid with and without Docker

The above illustration show the multiple nodes connected with the main hub running the selenium code and the node itself is inside the container with the hub, but we have a different setup.

  1. We have our selenium code that we are going to dockerize and run.
  2. The standalone image for the chrome driver will be running on http://localhost:4444. So we just need to tell our code to use that as a web-driver.

What Problem does this solution solves?

We don’t need to dockerize the chrome driver with our code and that would save us from number of errors. So we will be keeping our driver independent of our code and vise versa.

1. Dockerize the Code

Below is the Dockerfile used to dockerize the code and whenever the container is set to run, it runs the main file.

FROM python:3.10


WORKDIR /usr/src/app


COPY requirements.txt ./


RUN pip install --upgrade pip


RUN pip install --no-cache-dir -r requirements.txt


COPY . .


CMD ["python", "./ebilling.py"]

if you don’t know how to get the requirements.txt file, then just type:

pip freeze > requirements.txt

Before dockerizing your code, you need to ensure that you setup your webdriver in your main file.

from selenium.webdriver.chrome.options import Options

hub_url = "http://my-selenium-grid-driver:4444"
options = Options()

driver = webdriver.Remote(command_executor=hub_url, options=options)

The hub url is nothing, but the name of the container running my webdriver. I’ll let you know how to setup that.

So, now before using your chrome driver make sure to pull the image and run it.

2. Selenium Chrome Docker Image

Before pulling the image make sure you create a single network where both these containers reside and that’s pretty easy with docker.

docker network create my-selenium-network
docker network ls #THIS LISTS DOWN ALL THE NETWORKS

Now let’s just run the selenium image.

docker run -d --name my-selenium-grid-driver --network my-selenium-network -p 4444:4444 -p 7900:7900 --shm-size="2g" selenium/standalone-chrome:latest

Once this spin up the container, it would look like this.

Now after spinning up the driver container, you need to run your code and make it use this container.

3. Building and running our Code Container

docker build -t my-selenium-code-container .
docker run -d --name my-selenium-code-container --network my-selenium-network my-selenium-code-container

Volla! Now you have your code container, using a remote driver on the same machine, which you can easily migrate and use where-ever you want.

Thanks for reading ❤

--

--

Ahson Shaikh

DevOps Engineer with 3 years of experience in cloud and on-premises environments, specializing in Python automation with Selenium, currently working at Arpatech