- 특정 사이트에 새 글이 올라오면 텔레그램 봇을 통해 알림을 보내주는 코드를 작성했다.
- 정적 사이트의 경우 BS4를 통해 파싱하는 것이 효율적이고 가볍지만, 내가 목표로 하는 사이트의 경우 동적 페이지다(글 로딩을 위해 JS 실행 필요). 따라서 셀레니움을 사용한다.
- 아래 사항들을 알게 되었다.
* 셀레니움 실행을 위해서는 chromedriver를 각 PC의 크롬 버전과 호환되도록 하는 것이 중요하여 시행착오를 겪었으며, 아래 코드를 통해 자동으로 최신 chromedriver를 사용할 수 있다.
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)
* 셀레니움의 By 기능을 통해 find_element() 코드를 보기 좋게 유지보수 할 수 있다.
* options.add_argument('--headless') 코드를 통해 브라우저 팝업 없이 셀레니움을 실행할 수 있다.
* 해당 페이지의 새 글의 상대적 위치가 변하지 않는다면 Xpath를 통해 접근하는 것이 편하다.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from webdriver_manager.chrome import ChromeDriverManager
from datetime import date
import time
import telegram
# Fixed values
TOKEN = '토큰_확인_후_입력'
CHAT_ID = '챗_아이디_확인_후_입력'
url = "타겟_사이트"
#set run interval
run_interval = 60
# Telegram bot
bot = telegram.Bot(token=TOKEN)
#크롬 옵션 설정
options = Options()
options.add_argument('--headless')#run without brouwer popup
#Automatic use of lateset webdriver version setting, option setting
browser = webdriver.Chrome(service=Service(ChromeDriverManager().install()),options=options)
#Converse date to str, substitute bar to dot
today = date.today().isoformat().replace('-', '.')
print(today)
#compare recent notice to new notice and if it is not the same, send telegram message
while True:
try:
#run the first scrapping
browser.get(url)
elem_post = browser.find_element(By.XPATH,"//*[@id='info_notice']/table/tbody/tr[1]/td[2]/a")
#save the first sacapping result
old_notice = elem_post.text
#set interval
time.sleep(run_interval)
#run the second scrapping
browser.get(url)
elem_post = browser.find_element(By.XPATH,"//*[@id='info_notice']/table/tbody/tr[1]/td[2]/a")
#save the first sacapping result
new_notice = elem_post.text
if new_notice == old_notice:
print('new_notice:',new_notice)
print('old_notice:',old_notice)
print('새글 없음')
pass
else:
bot.sendMessage(chat_id=CHAT_ID, text = new_notice)
print('new_notice:',new_notice)
print('old_notice:',old_notice)
print('send message')
# To handle exceptions
except Exception as e:
print(e)
'코딩 > 뭔가 만들어 보기' 카테고리의 다른 글
[Python] 2015~2020년 대한민국 근로소득 불평등도는 어떻게 변했을까?(지니계수, 로렌츠곡선) (0) | 2022.12.11 |
---|---|
[Python] Selenium과 python selenium bot을 이용하여 취소표 빈자리 알림 보내기 (1) | 2022.09.29 |
근로소득 구간별 세금 부담 비율 (0) | 2021.09.29 |
내 연봉, 근로소득자 중 상위 몇 퍼센트일까?(+ 세금은 얼마나 내고 있을까?) (0) | 2021.09.07 |
연말정산 계산기 만들어보기(1) (1) | 2021.08.29 |
댓글