본문 바로가기
코딩/뭔가 만들어 보기

[Python] 특정 페이지에 새 글이 올라오면 알림을 보내는 코드

by Say_Young 2022. 9. 14.

- 특정 사이트에 새 글이 올라오면 텔레그램 봇을 통해 알림을 보내주는 코드를 작성했다. 

- 정적 사이트의 경우 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)

 

댓글