To start a Selenium server with Chrome browser in headless mode, the code sets the DISPLAY environment variable, runs the Java Virtual Machine, and specifies the path to the Selenium standalone JAR file. The command also sets JVM system properties to customize the Chrome browser's behavior, including running in full-screen, disabling sandboxing, and running in incognito mode.
export DISPLAY=:0
java -Dwebdriver.chrome.driver="/usr/bin/chromedriver" -Dwebdriver.chrome.args="--start-fullscreen --no-sandbox --incognito" -jar /opt/selenium/selenium-server-standalone.jar
bash
#!/bin/bash
# Define constants for display and chromedriver location
LOCAL_DISPLAY=:0
CHROMEDRIVER_PATH="/usr/bin/chromedriver"
# Define command line options for chromedriver
CHROMEDRIVER_ARGS=(
"--start-fullscreen"
"--no-sandbox"
"--incognito"
)
# Define the Selenium Server JAR location
SELENIUM_JAR="/opt/selenium/selenium-server-standalone.jar"
# Define a function to start the Selenium Server
start_selenium_server() {
# Set the DISPLAY environment variable
export DISPLAY=$LOCAL_DISPLAY
# Start the Selenium Server with custom chromedriver args
java -Dwebdriver.chrome.driver=$CHROMEDRIVER_PATH \
-Dwebdriver.chrome.args=$(IFS=,; echo "${CHROMEDRIVER_ARGS[*]}") \
-jar $SELENIUM_JAR
}
# Start the Selenium Server
start_selenium_server
Code Breakdown
Purpose: Start a Selenium server with Chrome browser in headless mode.
Line-by-Line Explanation:
export DISPLAY=:0
java
-Dwebdriver.chrome.driver="/usr/bin/chromedriver"
-Dwebdriver.chrome.args="--start-fullscreen --no-sandbox --incognito"
--start-fullscreen
: Runs the browser in full-screen mode.--no-sandbox
: Disables sandboxing, which allows the browser to run outside of a sandbox container.--incognito
: Runs the browser in incognito mode.-jar /opt/selenium/selenium-server-standalone.jar