Selenium python and docker

WBOY
Release: 2024-08-27 06:02:32
Original
562 people have browsed it

Selenium python and docker

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
Copy after login
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 
Copy after login

You can then run this Dockerfile in a docker-compose, for example.

services:
  bot:
    build: selenium-test
Copy after login

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)

Copy after login

You can then use a undetected_chromedriver as selenium like this:

self.driver.execute_script("console.log("Hello")
Copy after login

The above is the detailed content of Selenium python and docker. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!