from pathlib import Path
from tempfile import TemporaryDirectory
import os
import shutil
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
HTML = """
Selenium headless demo
Headless browser ready
"""
options = Options()
options.add_argument("--headless=new")
options.add_argument("--window-size=1280,720")
for browser_name in ("google-chrome", "chromium", "chromium-browser"):
browser_path = shutil.which(browser_name)
if browser_path:
options.binary_location = browser_path
break
if hasattr(os, "geteuid") and os.geteuid() == 0:
options.add_argument("--no-sandbox")
options.add_argument("--disable-dev-shm-usage")
driver_path = shutil.which("chromedriver")
service = Service(driver_path) if driver_path else Service()
with TemporaryDirectory() as tmpdir:
page = Path(tmpdir) / "headless-demo.html"
page.write_text(HTML, encoding="utf-8")
driver = webdriver.Chrome(service=service, options=options)
try:
driver.get(page.as_uri())
window_size = driver.get_window_size()
print(f"title: {driver.title}")
print(f"heading: {driver.find_element(By.TAG_NAME, 'h1').text}")
print(f"window_size: {window_size['width']}x{window_size['height']}")
print(f"browser: {driver.capabilities.get('browserName')}")
finally:
driver.quit()