search
HomeBackend DevelopmentPython TutorialHow to Set Up Selenium as a Linux Daemon with systemd

How to Set Up Selenium as a Linux Daemon with systemd

Setting up and running Chrome and Selenium on the ubuntu or debian. The guide is based on ubuntu 22.04

Selenium is great for automating web tasks, but keeping a bot running 24/7 on a server can be tricky. By using systemd, you can run your Selenium bot as a background service (daemon), ensuring it runs reliably and restarts on failure. This guide will walk you through the steps to set it up, with a focus on configuring it for a Linux VPS.

Table of Contents

  1. Installing Google Chrome

  2. Setting up the virtual environment

  3. Installing necessary packages

  4. Creating the Python script

  5. Setting up the systemd service

    • Adding ENV variables (optional)
    • Service file
    • Running the service
  6. Fixing block buffering issues

    • Using the -u flag
    • Using the Print flush argument
  7. Accessing logs using journalctl

  8. References


Installing Google Chrome

First, update all packages.

sudo apt update

Download the stable Google Chrome package.

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

Install Google Chrome.

sudo apt install -y ./google-chrome-stable_current_amd64.deb

Check the installed Google Chrome version.

google-chrome --version

Setting up the virtual environment

These steps are not mandatory if you're solely running the Selenium bot on your machine. However, it's recommended if you're working on other projects or need isolated environments.

Lets create our virtual environment.

python3 -m venv venv

Activate the virtual environment.

source venv/bin/activate

Installing necessary packages

Now, install selenium and webdriver-manager.

pip install selenium
pip install webdriver-manager

The purpose of webdriver-manger is to simplify the management of binary drivers for different browsers. You can learn more about it in its documentation.


Creating the Python script

## main.py

from selenium import webdriver
## ---- Use for type hint ---- ##
from selenium.webdriver.chrome.webdriver import WebDriver
## --------------------------- ##
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager


def create_chrome_web_driver_connection(headless: bool,
                                       detach:bool,
                                       use_sandbox: bool,
                                       use_dev_shm: bool,
                                       window_width: int = 1052,
                                       window_height: int = 825
                                       ) -> WebDriver:

    service = Service(ChromeDriverManager().install())
    options = Options()
    options.add_experimental_option("detach", detach)
    options.add_argument(f"--window-size={window_width},{window_height}")
    options.add_argument("--disable-extensions")
    options.add_argument("--disable-renderer-backgrounding")
    options.page_load_strategy = 'normal'

    if not use_sandbox:
        options.add_argument('--no-sandbox')
    if not use_dev_shm:
        options.add_argument('--disable-dev-shm-usage')
    if headless:
        options.add_argument("--headless=new")

    driver = webdriver.Chrome(service= service, options=options)

    return driver



if "__main__" == __name__:
    driver =  create_chrome_web_driver_connection(headless= True,
                                                 detach= False,
                                                 use_sandbox= False,
                                                 use_dev_shm= False)

    driver.get('https://python.org')
    print(driver.title)

    driver.close()

options.add_experimental_option("detach", detach) :

  • This allows you to configure whether the Chrome browser remains open after the script has finished executing.
  • If detach is True, the browser window will stay open even after the WebDriver session ends.

options.add_argument(f"--window-size={window_width},{window_height}") :

  • This sets the window size for the browser in terms of width and height.

You can remove this line if you want to.
If you plan to run Selenium in headless mode, make sure to set the window size this way; otherwise, in my experience, the default window size might be too small.

You can check your window size with this command driver.get_window_size()

options.add_argument("--disable-extensions") :

  • Extensions can interfere with automated browser interactions, so disabling them can improve stability.

options.add_argument("--disable-renderer-backgrounding") :

  • This prevents Chrome from deprioritizing or suspending background tabs.
  • This can be useful when performing actions across multiple tabs.

options.page_load_strategy = 'normal' :

  • This sets the page load strategy to normal, meaning Selenium will wait for the page to load fully before proceeding with further commands.
  • Other options include eager (wait until the DOMContentLoaded event) and none (not waiting for the page to load), you can learn more about it here.

options.add_argument('--no-sandbox') :

  • The sandbox is a security feature of Chrome that isolates the browser's processes.
  • Disabling it (--no-sandbox) can be useful in some testing environments (e.g., in Docker containers or when executing the script as the root user) where the sandbox causes permission issues or crashes.

options.add_argument('--disable-dev-shm-usage') :

  • /dev/shm is a shared memory space often used in Linux environments. By default, Chrome tries to use it to improve performance.
  • Disabling this (--disable-dev-shm-usage) can prevent crashes in environments where the shared memory is limited.

options.add_argument("--headless=new") :

  • This enables headless mode, which runs Chrome without a GUI.
  • Headless mode is useful for running in environments without a display, such as CI/CD pipelines or remote servers.

Setting up the systemd service

Adding ENV variables (optional)

In case your selenium program needs to use environment variables there are two ways in which you can achieve this:

  1. Using a .env file with a library like python-dotenv (the more common/popular method).

  2. Using systemd’s built-in option to set up an Environment File.

For this example, we will use the second option.

First, let's create create a conf.d directory inside the /etc directory.

sudo apt update

Next, create a plain text file(this will be our environment file).

sudo apt update

Now you can add your environment variables to the file we just created.

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

Modify the Python script to use the environment variables.

sudo apt install -y ./google-chrome-stable_current_amd64.deb

Service file

You need to create a service file inside this /etc/systemd/system/ directory; this is where systemd units installed by the system administrator should be placed.

google-chrome --version

For this example im going to assume that you are in a VPS and you want to run the service as the root user.

[!WARNING]
The service will run with root (administrator) privileges. This gives it full access to the system, but running as root is usually avoided unless necessary for security reasons.

Add this to the service file.

python3 -m venv venv

[Unit] Section

This section defines metadata and dependencies for the service.

Description=Selenium Bot Service : Provides a short description of what the service does. In this case, it describes it as the "Selenium Bot Service." This description is used in system logs and by systemctl to identify the service.

After=network.target: This ensures that the service starts only after the network is available. The network.target is a systemd target that indicates basic networking functionality is up.

[Service] Section

This section specifies the configuration of the service itself, including how it runs, which user runs it, and what to do if it fails.

User : Specifies the user under which the service will run. Here, it’s set to root.

EnvironmentFile : Specifies a file that contains environment variables used by the service.

WorkingDirectory: Specifies the directory from which the service will run. This is the working directory for the service process. Here, the bot files are stored in /root/selenium_bot/

ExecStart : Defines the command to start the service. Here, it runs the main.py file in /root/selenium_bot/

Restart=on-failure : Configures the service to restart automatically if it exits with a failure (i.e., non-zero exit status). This is useful to ensure that the bot service remains running, even if there are occasional failures.

RestartSec=5s : Specifies the delay between restarts in case of failure. In this case, the service will wait 5 seconds before attempting to restart after a failure.

StandardOutput=journal : Redirects the standard output (stdout) of the service to the systemd journal, which can be viewed using journalctl. This is useful for logging and debugging purposes.

StandardError=journal : Redirects the standard error (stderr) output to the systemd journal. Any errors encountered by the service will be logged and can also be viewed using journalctl

[Install] Section

This section defines how and when the service should be enabled or started.

WantedBy=multi-user.target : Specifies the target under which the service should be enabled. In this case, multi-user.target is a systemd target that is reached when the system is in a non-graphical multi-user mode (common in servers). This means the service will be started when the system reaches this target, typically when the system has booted to a multi-user environment.

To learn more about all the possible settings for a systemd service check the references

Running the service

Let's check that our service file is valid; if everything is okay, nothing should be displayed.

sudo apt update

Reload the systemd configuration, looking for new or modified units(services).

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

Start/Restart your service.

sudo apt install -y ./google-chrome-stable_current_amd64.deb

Stop your service.

google-chrome --version

Check your service status.

python3 -m venv venv

Do this if you want your service to start automatically at boot.

source venv/bin/activate

Fixing block buffering issues

In python when you run your script in an interactive environment( e.g., when you manually run python3 filename.py in a terminal) Python uses line buffering. This means that output, like the one from a print() statement, is shown immediately.

However, when the Python program is run in a non-interactive environment (this is our case), the output will use block buffering. This means that the program will hold onto its output in a buffer until the buffer is full or the program ends, delaying when you can see logs/output.

You can learn more about how python's output buffering works here.

Since we want to view logs and output in real-time, we can address this issue in two ways.

Using the -u flag

The python3 docs tells us this.

-u Force the stdout and stderr streams to be unbuffered. This option has no effect on the stdin stream

By using the -u flag, Python operates in a fully unbuffered mode for both stdout and stderr. This means that each byte is sent directly to the terminal (or any output stream like a log file) as soon as it is produced. No buffering takes place at all.

Every character that would typically go to stdout (like from print() statements or errors) is immediately written, byte-by-byte, without waiting for a full line or buffer to accumulate.

To use this option run your script like this:

sudo apt update

If you go with this option make sure to modify the ExecStart inside the service file.

wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb

Using the Print flush argument

In Python, the print() function buffers its output by default, meaning it stores the output in memory and only writes it out when the buffer is full or the program ends. By using flush=True, you can force Python to flush the output immediately after the print() call, ensuring that the output appears right away.

sudo apt install -y ./google-chrome-stable_current_amd64.deb

Accessing logs using journalctl

To view the full log history of your systemd unit (service), use the following command.

google-chrome --version

To monitor logs in real time, use the -f flag. This will show only the most recent journal entries, and continuously print new entries as they are appended to the journal.

python3 -m venv venv

References

  • https://github.com/password123456/setup-selenium-with-chrome-driver-on-ubuntu_debian
  • https://www.selenium.dev/documentation/webdriver/drivers/options/
  • https://www.lambdatest.com/blog/selenium-page-load-strategy/
  • https://pypi.org/project/webdriver-manager/
  • https://pypi.org/project/python-dotenv/
  • https://wiki.archlinux.org/title/Systemd
  • https://man.archlinux.org/man/systemctl.1
  • https://man.archlinux.org/man/systemd.service.5.en#EXAMPLES
  • https://man.archlinux.org/man/systemd-analyze.1
  • https://docs.python.org/3/using/cmdline.html#cmdoption-u
  • https://realpython.com/python-flush-print-output/
  • https://man.archlinux.org/man/journalctl.1

The above is the detailed content of How to Set Up Selenium as a Linux Daemon with systemd. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading?Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.