코알못

[selenium] 손쉽게 브라우저 자동 캡쳐 기능 만들기 본문

PYTHON

[selenium] 손쉽게 브라우저 자동 캡쳐 기능 만들기

코린이s 2021. 5. 2. 15:55
728x90

셀레니움을 이용하면 브라우저 컨트롤이 가능하다!

여러 브라우저중에 저자는 크롬을 사용하여 브라우저 캡쳐 기능을 구현해보겠다!

일단 크롬드라이버를 설치해보자! (서버에 설치된 크롬 버전에 맞게 설치 해야한다.)

- 설치 링크 : chromedriver.chromium.org/downloads

 

ChromeDriver - WebDriver for Chrome - Downloads

Current Releases If you are using Chrome version 91, please download ChromeDriver 91.0.4472.19 If you are using Chrome version 90, please download ChromeDriver 90.0.4430.24 If you are using Chrome version 89, please download ChromeDriver 89.0.4389.23 If yo

chromedriver.chromium.org

셀레니움 캡쳐를 위한 파이썬 코드를 작성한다!

저자는 전체 화면 한 뒤 캡쳐하는 간단한 기능을 만들었지만,

아래 링크에서 브라우저 컨트롤 방법을 참고하여 핸들링 한 뒤 캡쳐하면 된다.

- www.selenium.dev/documentation/ko/getting_started/

 

시작하기 :: Selenium 문서

시작하기 Selenium이 처음이신가요? 빠르게 시작할 수 있도록 돕기 위해서 몇 가지 자료를 준비했습니다.

www.selenium.dev

# 환경
- mac Catalina 10.15.6
- Python 3.7.6
- chrome 90.0.4430

// capture.py
from selenium import webdriver
import time

driver = webdriver.Chrome("/Users/hongyoolee/document/study/capture/chromedriver")
try:
	driver.get("https://co-de.tistory.com/")
	# 스크린샷 전에 시간 두기(로딩이 느릴수도 있으니)
	time.sleep(3)
	# 창 최대화
	driver.maximize_window()
	# 스크린샷 찍기
	driver.save_screenshot("/Users/hongyoolee/document/study/capture/capture.png")
	# 종료 (모든 탭 종료)
	driver.quit()
	print("### capture complete")
except Exception as e:
	print('### error msg :: ', e)
	driver.quit()

 

위 코드는 브라우저를 화면에 띄운뒤 캡쳐를 진행 하나, 아래와 같이 headless 옵션을 주면 백그라운드로 실행할 수 있다.

# headless 모드(background)
options = webdriver.ChromeOptions()
options.add_argument('headless')
options.add_argument('window-size=1920x1080')

driver = webdriver.Chrome("/Users/hongyoolee/document/study/capture/chromedriver", options=options)

 

selenium webdriver을 종료하는 명령어는 두가지가 있다.

driver.close() : 활성화 되어있는 탭만 종료

driver.quit() : 모든 탭 종료

driver.quit() 를 사용하여 종료되지 않은 webdriver가 없도록 하여 메모리의 누수가 발생하지 않도록 하자!

 

그러나 정상적이지 않은 종료로 인해 driver.quit() 가 실행 되기 전에 프로세스가 끝나게 되면 남아있는 프로세스가 있기에

아래와 같은 파이썬 파일을 추가로 생성한다.

// kill_chrome.py
import os
os.system("pkill -9 -i chrome")
print("### delete complete")

해당 파이썬 파일을 실행하는 스크립트를 작성한다.

// start_capture.sh
#!/bin/bash
# capture
/Users/hongyoolee/miniconda3/bin/python /Users/hongyoolee/document/study/capture/script/capture.py >> /Users/hongyoolee/document/study/capture/logs/capture.log 2>&1

# chrome browse kill
/Users/hongyoolee/miniconda3/bin/python /Users/hongyoolee/document/study/capture/script/kill_chrome.py >> /Users/hongyoolee/document/study/capture/logs/capture.log 2>&1

위 파이썬 파일들을 crontab 에 등록하여 자동화 하자!

  • 형식 : * * * * *
  • 의미 : 분(0-59) 시간(0-23) 일(1-31) 월(1-12) 주(일요일=0-6)
# 배치 수정
$ crontab -e
10 00 * * * /Users/hongyoolee/document/study/capture/script/start_capture.sh

# 배치 확인
$ crontab -l
10 00 * * * /Users/hongyoolee/document/study/capture/script/start_capture.sh

 

# 결과

- 로그

### capture complete
### delete complete

- 캡쳐

완료 !!

:: github.com/works-code/py-selenium

 

works-code/py-selenium

python-selenium. Contribute to works-code/py-selenium development by creating an account on GitHub.

github.com

 

728x90
Comments