본문 바로가기

스크립트

Docker 컨테이너에서 Python Selenium 실행하기

반응형

Docker 컨테이너에서 Python Selenium 실행하기

Docker 컨테이너에서 Selenium을 실행하려면 다음 구성 요소가 필요합니다.

Python
Selenium
Browser (Firefox 또는 Chrome)
WebDriver (geckodriver 또는 chromedriver)

Docker 기본 Python 이미지는 브라우저가 포함되어 있지 않기 때문에 브라우저와 WebDriver를 직접 설치해야 합니다

1. Python 컨테이너 실행

Python 공식 이미지를 이용하여 컨테이너를 실행합니다.

docker run -it --rm python:3 bash

2. 필수 패키지 설치

Firefox 실행에 필요한 라이브러리와 기본 도구를 설치합니다.

apt update

apt install -y \
    firefox-esr \
    wget \
    vim \
    ca-certificates \
    libgtk-3-0 \
    libdbus-glib-1-2

설치 확인

firefox --version

3. Geckodriver 설치

Firefox를 Selenium에서 제어하기 위해 Geckodriver(ARM64용 드라이버)를 설치합니다.

GECKO_VERSION=v0.36.0

wget https://github.com/mozilla/geckodriver/releases/download/${GECKO_VERSION}/geckodriver-${GECKO_VERSION}-linux-aarch64.tar.gz

tar -xvzf geckodriver-${GECKO_VERSION}-linux-aarch64.tar.gz

mv geckodriver /usr/local/bin/

chmod +x /usr/local/bin/geckodriver

설치 확인

geckodriver --version

4. Selenium 설치

Python 패키지 관리자인 pip를 사용하여 Selenium을 설치합니다.

pip install selenium

설치 확인

pip show selenium
728x90

5. Selenium 테스트 코드 작성

Docker 환경에는 GUI가 없기 때문에 Headless 모드를 사용해야 합니다.

vim browser_test.py
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service
import time

# Firefox 옵션 설정
options = Options()
options.binary_location = "/usr/bin/firefox"
options.add_argument("--headless")
options.add_argument("--no-sandbox")

# Geckodriver 경로 지정
service = Service("/usr/local/bin/geckodriver")

# 브라우저 실행
browser = webdriver.Firefox(service=service, options=options)

# 웹사이트 접속
browser.get("https://www.sangchul.kr")

# 페이지 제목 출력
print(browser.title)

# 잠시 대기
time.sleep(3)

# 브라우저 종료
browser.quit()

로케일 설정(UTF-8)

더보기

---

locales 패키지 설치

apt update
apt install -y locales

ko_KR.UTF-8 locale 생성

locale-gen ko_KR.UTF-8

환경 변수 설정

export LANG=C.UTF-8
export LC_ALL=C.UTF-8

---

6. Selenium 실행

Python 스크립트를 실행합니다.

python browser_test.py
변군이글루 블로그(Development)

7. 전체 동작 구조

Python Script
      │
      ▼
Selenium
      │
      ▼
Geckodriver
      │
      ▼
Firefox (Headless)

 

참고URL

- Selenium 공식 문서 : https://www.selenium.dev/documentation

- Geckodriver 다운로드 : https://github.com/mozilla/geckodriver/releases

 

728x90
반응형