[Heroku] 헤로쿠에서 ChromeDriver 사용하기
로컬에서 chromedriver를 쓸 때는 크롬드라이버를 다운받은 후, 폴더에 넣고
local path를 이용해서 chromedriver를 실행시켜주었습니다.
from selenium import webdriver
import os
BASE_DIR = Path(__file__).resolve().parent
chrome_driver_path = os.path.join(BASE_DIR, 'chromedriver')
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
driver = webdriver.Chrome(chrome_driver_path, options=chrome_options)
driver.get("some url")
...
이대로 Heroku에 배포하면 chromedriver를 찾을 수 없다고 나옵니다.
그럼 Heroku에서 chromedriver를 사용하려면 어떻게 해야할까요?
Heroku는 chromedriver buildpack을 제공하는 데, 그것을 사용하면 됩니다.
1) Buildpacks
Heroku > 내 앱 > Settings로 들어가줍니다.
Buildpacks에서 Add buildpack을 누르고
아래 두개의 URL을 입력해줍니다.
- Headless Google Chrome: https://github.com/heroku/heroku-buildpack-google-chrome
- Chromedriver: https://github.com/heroku/heroku-buildpack-chromedriver
그러면 아래 사진처럼 빌드팩이 추가됩니다.
(참고로 맨 위의 python은 원래 기본으로 추가되어있었던 것입니다.)
2) Config Vars
Config Vars 로 가서 key, value를 아래처럼 추가해주세요
- CHROMEDRIVER_PATH = /app/.chromedriver/bin/chromedriver
- GOOGLE_CHROME_BIN = /app/.apt/usr/bin/google-chrome
3) Your Code
위에서 추가한 환경변수를 가지고 chromedriver를 실행시켜주도록 코드를 바꿔줍니다.
from selenium import webdriver
import os
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
driver = webdriver.Chrome(executable_path=os.environ.get("CHROMEDRIVER_PATH"), chrome_options=chrome_options)
driver.get("some url")
...
참고로 위의 옵션 중, --no-sandbox 은 꼭 필요한지 잘 기억이 안납니다,,
(보안을 약하게 하는 옵션인 것 같은데, 작업하고 한참 후에 글을 쓰는 거라 기억이 안나네요ㅠㅠ 우선 빼고 배포해보시길 추천드립니다.)
[ Reference ]
https://www.andressevilla.com/running-chromedriver-with-python-selenium-on-heroku/
Running ChromeDriver with Python Selenium on Heroku - Andres Sevilla
I have recently been experimenting with the Heroku platform for building basic web apps, and my experience has been nothing but excellent so far. At least, that was until I tried to incorporate Selenium into one of my Python projects. Selenium is a Python
www.andressevilla.com