목적: 정해진 시간에 반복하여 Crawler를 돌리기
크롤러를 만들었고 이제 데이터를 수집하고 싶거나, 정해진 시간에 크롤러가 특정 작업을 하게 하고 싶다. 매번 사람이 번거롭게 프로그램을 실행하기 보다, 컴퓨터가 알아서 작업을 하게 스케쥴을 작성하고 싶어진다.
우분투에서는 Cron을 이용하여, 정해진 시간 단위/패턴 마다 특정 command를 실행하게 할 수 있다.
기본 문법 예시는 다음과 같다.
*/10 * * * * /usr/bin/python script.py
앞에서부터 분 / 시간 / 일 / 월 / 요일 command 순서이다. */10은 매 10분 마다를 의미하고, 5번째 별에 4-6을 입력하면 목, 금, 토에 작동을 한다. 자세한 사용법은 인터넷에 찾아보면 잘 나와있다.
터미널에서 crontab -e 로 편집기를 열어서 위 스크립트를 붙여넣고 저장하면 그 때부터 작동한다.
그러나…….. script.py가 selenium + chromedriver를 사용한 코드이면… 아래와 같은 에러메세지를 출력한다….
Exception in thread <name>:
Traceback (most recent call last):
File "/usr/lib64/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/lib64/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/path/to/script.py", line 53, in start
self.site_scrape(test_run)
File "/path/to/script.py", line 65, in site
self.driver = webdriver.Chrome(chrome_options=options)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/chrome/webdriver.py", line 69, in __init__
desired_capabilities=desired_capabilities)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 98, in __init__
self.start_session(desired_capabilities, browser_profile)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 188, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 256, in execute
self.error_handler.check_response(response)
File "/home/<user>/.virtualenvs/selenium/lib64/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.38.552522 (437e6fbedfa8762dec75e2c5b3ddb86763dc9dcb),platform=Linux 4.14.12-x86_64-linode92 x86_64)
마음이 아프다…
인터넷에서 검색했을 때는 다들 쉬워보였는데…
해결법으로 아래와 같은 세 가지를 시도해볼 수 있다.
0. 혹시나 selenium에서 chromedriver를 호출할 때 실제로 browser가 켜지도록 (보이도록) 되어 있는지 확인.. 꺼서 background에서 작동하게 한다..
1. Background에서 작동하는 cron에서 browser를 키려는 경우 충돌이 발생할 수 있다고 한다… (https://stackoverflow.com/questions/23908319/run-selenium-with-crontab-python) 위 글에서 제시한 해결책으로는 DISPLAY=:0 을 포함시키는 것이다. 예를 들어서… 아래처럼.
DISPLAY=:0
*/10 * * * * /usr/bin/python script.py
2. Cron은 무척 제한적인 PATH만 사용한다고 한다… 스크립트에 path를 적어 넣어 임시로 문제를 해결할 수 있다.. (https://stackoverflow.com/questions/2388087/how-to-get-cron-to-call-in-the-correct-paths)
터미널에서 아래와 같은 과정을 거치면…
# echo PATH=$PATH > tmp.cron
# echo >> tmp.cron
# crontab -l >> tmp.cron
# crontab tmp.cron
우분투에서 사용하고 있는 PATH가 crontab 스크립트에 복사 붙여 넣기가 되어있다.