[Ubuntu Cron] Automating a Chrome Driver Crawler

목적: 정해진 시간에 반복하여 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 스크립트에 복사 붙여 넣기가 되어있다.

광고

[keychron] set function keys(f1-f12) to work on Ubuntu

According to the cheatsheet comes with the the products, one can press fn + X + L more than 3 secs to switch between function and multimedia keys.

However, this doesn’t work on Ubuntu. No matter how many times (even, odd… -_-) I try, the f1-f12 always perform as multimedia keys.

In order to change them to work as function key we can change the following settings:

ctrl + alt + t # Turn on the terminal

cd /sys/module/hid_apple/parameters
sudo nano ./fnmode

Then change the fnmode’s content from 1 to 0

try fn + X + L (more than 3 secs until the keyboard lights)

yay it works!

source: https://devlog.jwgo.kr/2019/12/13/how-to-fix-fn-key-not-working-between-keychron-and-ubuntu/

[Matplotlib] 한글 폰트 추가

https://financedata.github.io/posts/matplotlib-hangul-for-ubuntu-linux.html

위 사이트를 참고하면 굉장히 상세하게 (한글) 폰트 추가 과정이 나와있다. (감사합니닷)

Jupyter notebook으로 코딩 중 위 문제를 만나게 되면, 자칫 Jupyter notebook을 켜놓고 위의 과정을 진행하게 되어, 시키시는 대로 따라했음에도 Matplotlib에서 새로 추가한 폰트를 인식하지 못하는 경우가 생긴다.

위 사이트 [글꼴 설치] 파트에서 아래 과정을 진행할 때 꼭 Jupyter Notebook이나 이미 matplotlib를 호출해 놓고 있는 프로세스를 종료하고 해야한다!

$ sudo cp /usr/share/fonts/truetype/nanum/Nanum* /usr/local/lib/python3.4/dist-packages/matplotlib/mpl-data/fonts/ttf/
$ rm -rf /home/ubuntu/.cache/matplotlib/*

Jupyter notebook 끄기 ! -> 위의 코드 진행 -> 다시 키기 ! :::: 마법처럼 되었다! 끝!

예시:

import matplotlib as mpl

import matplotlib as mpl
import matplotlib.font_manager as fm

set(sorted([f.name for f in fm.fontManager.ttflist]))
#---> 사용 가능한 폰트들이 뜬다!!\

#이 중 NanumBarunGothic을 사용하려면, 
mpl.rcParams['font.family'] = 'NanumBarunGothic' 

#폰트를 바꾸고 그래프를 그리면 -부호가 안 나오는 경우가 있는데 아래와 같이 하면 나온당.
matplotlib.rcParams['axes.unicode_minus'] = False

[Javascript] Entering Letter grades Automatically at UMEG

Entering letter grades automatically at UMEG

Putting letter grades in UMEG with 300 + clicks is cumbersome and prone to mistakes, especially for large sized classes.

An  alternative is to use Canvas(elms) to convert grades into UMEG. However, the functions provided by Canvas are rather restrictive (and slow). And we don’t want to create numerous alarms to be sent to students.

So we can try using the following script at UMEG to fill out the grades automatically.

var t = document.getElementsByTagName(“table”)[5];
var trs = t.getElementsByTagName(“tr”);

// input the grades you want to enter following the order in UMEG (name – ascending order)
var grades = [“A+”, “C”, “D”];

function to_num(letter) {
var i = null;
var j = 2;
if (letter[0] == “A”) {
i = 1
} else if (letter[0] == “B”) {
i = 2
} else if (letter[0] == “C”) {
i = 3
} else if (letter[0] == “D”) {
i = 4
}
if (letter.slice(-1) == “+”) {
j = 1
} else if (letter.slice(-1) == “+”) {
j = 3
}
return [i, j]
}

// change num as the number of students in your class
var num = 374
for (var i = 0; i<num; i++) {
var str_ = “grd” + i
var letter = to_num(grades[i])
var grade = trs[9*i + 1].getElementsByTagName(“td”)[letter[0]*4-2 + letter[1]].getElementsByTagName(“input”)[str_]
grade.checked = false;
grade.checked = true;
console.log(i)
}