Hi, I show how I use selenium (or undetected_chromedriver) in a docker container.
I - Dockerfile
I'm using a docker python image and adding chromdriver and chromium to browse a website.
The first step is to create the requirements.txt
file. Personally, I use the undetected-chromedriver
library, which takes selenium
undetected-chromedriver==3.5.5
FROM python:3.10
COPY ../.. .
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google-chrome.list'
RUN apt-get -y update
RUN apt-get install -y chromium
# install chromedriver
RUN apt-get install -yqq unzip
RUN wget -O /tmp/chromedriver.zip http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip
RUN unzip /tmp/chromedriver.zip chromedriver -d /usr/local/bin/
ENV DISPLAY=:99
RUN pip install -r requirements.txt
CMD python -u app.py
You can then run this Dockerfile in a docker-compose, for example.
services:
bot:
build: selenium-test
II - Script
In the second step, I need to add two options for working in a container.
I add :
--no-sandbox
--disable-setuid-sandbox
Here is an example with python
class App:
options: uc.ChromeOptions
driver: uc.Chrome
def __init__(self):
self.options = uc.ChromeOptions()
self.options.arguments.extend(["--no-sandbox", "--disable-setuid-sandbox"])
self.driver = uc.Chrome(headless=True, use_subprocess=False)
You can then use a undetected_chromedriver as selenium like this:
self.driver.execute_script("console.log("Hello")