From 8375843dd3c30bda04d2507123149430d0882825 Mon Sep 17 00:00:00 2001 From: Stephen Kent Date: Sun, 28 Jan 2024 00:41:24 -0800 Subject: [PATCH] Include undetected_chromedriver binary in Docker image --- Dockerfile | 1 + pyproject.toml | 1 + safeway_coupons/chrome_driver.py | 37 ++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/Dockerfile b/Dockerfile index f61776d..af9def6 100644 --- a/Dockerfile +++ b/Dockerfile @@ -29,6 +29,7 @@ COPY docker/entrypoint / COPY . /python-build RUN python3 -m pip install /python-build && rm -rf /python-build +RUN safeway-coupons-init-chromedriver ENTRYPOINT ["/usr/bin/tini", "--"] CMD ["/entrypoint"] diff --git a/pyproject.toml b/pyproject.toml index 16d307b..e5db4c5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,6 +48,7 @@ responses = "*" [tool.poetry.scripts] safeway-coupons = "safeway_coupons.app:main" +safeway-coupons-init-chromedriver = "safeway_coupons.chrome_driver:init" [tool.poetry-dynamic-versioning] enable = true diff --git a/safeway_coupons/chrome_driver.py b/safeway_coupons/chrome_driver.py index afb57f5..e3b9838 100644 --- a/safeway_coupons/chrome_driver.py +++ b/safeway_coupons/chrome_driver.py @@ -1,8 +1,23 @@ import contextlib +import subprocess +import sys +from pathlib import Path from typing import Iterator import undetected_chromedriver as uc # type: ignore +CHROMEDRIVER_PATH = ( + Path.home() + / ".local" + / "share" + / "undetected_chromedriver" + / "undetected_chromedriver" +) + + +class ChromeDriverDoesNotExist(Exception): + pass + @contextlib.contextmanager def chrome_driver(headless: bool = True) -> Iterator[uc.Chrome]: @@ -23,3 +38,25 @@ def chrome_driver(headless: bool = True) -> Iterator[uc.Chrome]: driver = uc.Chrome(options=options) yield driver driver.quit() + + +def chrome_driver_version() -> str: + if not CHROMEDRIVER_PATH.is_file(): + raise ChromeDriverDoesNotExist( + f"Error: {CHROMEDRIVER_PATH} does not exist" + ) + cmd = [str(CHROMEDRIVER_PATH), "--version"] + print(f"+ {' '.join(cmd)}", file=sys.stderr) + result = subprocess.run(cmd, capture_output=True) + return result.stdout.decode() + + +def init() -> None: + with contextlib.suppress(ChromeDriverDoesNotExist): + print(chrome_driver_version()) + return + print("Initializing Chrome Driver") + with chrome_driver() as driver: + print("Connect to example.com") + driver.get("https://example.com") + print(chrome_driver_version())