본문 바로가기
Programming/Code Archive

[파이썬] 실시간급상승검색어 자동 발송하는 봇 만들기 3: 웹크롤링과 메시지 발송을 수행하는 텔레그램 봇

by 지표덕후 2023. 8. 13.
반응형

실시간 급상승 검색어를 정해진 시간마다 크롤링해 텔레그램 메시지로 보내주는 봇을 제작합니다. (흰색 말풍선이 봇이 보낸 거고 녹색 말풍선은 접니다)
 

 
 
이 프로젝트는 아래 과업으로 이루어집니다:

텔레그램 봇 API 접근 권한 얻기
실시간 급상승 검색어 크롤링해 텍스트 파일로 저장
웹크롤링과 메시지 발송을 수행하는 텔레그램 봇 만들기(현재 글)

 
이번 포스팅에서는 
1) 봇이 실급검 사이트 접속해 검색어를 스크래핑(크롤링)하고
2) 그걸 발화 가능한 형식으로 바꿔서
3) 이용자에게 텔레그램으로 발송하는 일련의 과정을 구현합니다.
 

 
 
 

작업환경

1) 파이썬3.9(64bit)
2) 파이썬IDE : Pycharm
 
 
 

코드

▼ 필요한 라이브러리를 불러옵니다. 불러오려면 당연히 설치가 되어 있어야 되겠죠? (pip install 패키지명)
 

import telegram
from selenium import webdriver
from selenium.webdriver.common.by import By
import asyncio

 
 
 
Selenium 라이브러리로 실급검 사이트에 접속해서 원하는 정보를 스크래핑하는 코드입니다. 서두에 링크해둔 <실시간 급상승 검색어 크롤링해 텍스트 파일로 저장> 글에 코드에 대한 자세한 주석을 달아두었습니다. 이해가 어려우신 분들은 참고하세요.
 

# Set up the Chrome driver
driver = webdriver.Chrome()

# Navigate to the webpage
URL = "https://signal.bz/"
driver.get(url=URL)

crawling_date = driver.find_element(by=By.CSS_SELECTOR
                                    , value='#app > div > main > div > section > div > section > section:nth-child(2) > div:nth-child(1) > div:nth-child(1) > span').text

data = [crawling_date, '']

for j in [x for x in range(1, 3)]:
    for i in [x for x in range(1, 11)]:
        CSS_SELECTOR = f"#app > div > main > div > section > div > section > section:nth-child(2) > div:nth-child(2) > div > div:nth-child({j}) > div:nth-child({i}) > a > span.rank-text"
        # Use find_elements to get a list of WebElements
        results = driver.find_elements(by=By.CSS_SELECTOR, value=CSS_SELECTOR)

        for result in results:
            print(result.text)
            data.append(result.text)

driver.quit()

with open('realtime_keywords.txt', 'w') as f:
    for item in data:
        f.write(item + '\n')

 
▲ 위의 코드를 실행하면 realtime_keywords.txt라는 이름의 텍스트 파일이 생성됩니다. 바로 복사 붙여넣기 해서 메시지로 보내도 괜찮을 만큼 깔끔한 형식으로 실급검 키워드들이 정리되어 있지요. 
 

 
 
 
▼ 마지막 코드뭉치(code snippet)는 크롤링한 실급검 정보를 텔레그램 메시지로 발송하는 작업입니다. 
 
이 코드에 대해서는 서두에 링크해둔 <텔레그램 봇 API 접근 권한 얻기>에서 자세히 설명하고 있습니다. 참고해주세요. 
 
아래 CHAT_IDs 리스트(list)에는 두 개의 텔레그램 user ID가 요소로 있는데요. 하나는 제 것이고, 하나는 지인의 것입니다. 즉, 실급검 알람 메시지를 이 두 사람에게 발송하겠다는 거지요.
 

async def main():
    # Replace 'TOKEN' with your actual bot's API token
    TOKEN = '여러분이 발급 받은 API KEY'
    bot = telegram.Bot(token=TOKEN)

    # Replace 'CHAT_ID' with the chat ID of the recipient (user or group)
    CHAT_IDs = ['메시지 수신할 user ID 1', '메시지 수신할 user ID 2']

	# 크롤링한 텍스트 파일을 열어 문자열 변수 content에 할당 
    with open('realtime_keywords.txt', 'r') as file:
        content = file.read()

    # The message you want to send
    MESSAGE = content

    # Send the message using 'await'
    for CHAT_ID in CHAT_IDs:
        await bot.send_message(chat_id=CHAT_ID, text=MESSAGE)

# Run the coroutine
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

 
realtime_keywords.txt 파일만 이상 없다면, 위 코드 실행 시 메시지가 잘 발송될 겁니다. 
 

 
 
 
▼ 아래는 위의 코드를 합치기만 한, 최종 코드입니다.
 

import telegram
from selenium import webdriver
from selenium.webdriver.common.by import By
# from webdriver_manager.chrome import ChromeDriverManager

# Set up the Chrome driver
driver = webdriver.Chrome()

# Navigate to the webpage
URL = "https://signal.bz/"
driver.get(url=URL)

crawling_date = driver.find_element(by=By.CSS_SELECTOR
                                    , value='#app > div > main > div > section > div > section > section:nth-child(2) > div:nth-child(1) > div:nth-child(1) > span').text

data = [crawling_date, '']

for j in [x for x in range(1, 3)]:
    for i in [x for x in range(1, 11)]:
        CSS_SELECTOR = f"#app > div > main > div > section > div > section > section:nth-child(2) > div:nth-child(2) > div > div:nth-child({j}) > div:nth-child({i}) > a > span.rank-text"
        # Use find_elements to get a list of WebElements
        results = driver.find_elements(by=By.CSS_SELECTOR, value=CSS_SELECTOR)

        for result in results:
            print(result.text)
            data.append(result.text)

driver.quit()

with open('realtime_keywords.txt', 'w') as f:
    for item in data:
        f.write(item + '\n')

async def main():
    # Replace 'TOKEN' with your actual bot's API token
    TOKEN = '여러분이 발급 받은 API KEY'
    bot = telegram.Bot(token=TOKEN)

    # Replace 'CHAT_ID' with the chat ID of the recipient (user or group)
    CHAT_IDs = ['메시지 수신할 user ID 1', '메시지 수신할 user ID 2']

	# 크롤링한 텍스트 파일을 열어 문자열 변수 content에 할당 
    with open('realtime_keywords.txt', 'r') as file:
        content = file.read()

    # The message you want to send
    MESSAGE = content

    # Send the message using 'await'
    for CHAT_ID in CHAT_IDs:
        await bot.send_message(chat_id=CHAT_ID, text=MESSAGE)

# Run the coroutine
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(main())

 

반응형

댓글