https://mooooh.tistory.com/15

 

파이썬 네이버증권 뉴스 웹크롤링- (chat-gpt활용)

예전에 해봣던 네이버 웹 크롤링을 다시 활용해 보았다. 이번에는 소스코드를 작성하지 않고 chat-gpt를 활용하여 프로그램 소스코드를 자동 작성 하였다. 정말 신세계 였다. 간략하게나마 틀을

mooooh.tistory.com

지난 번에 올렸던 글을 활용하여 

본체에 합체하는 작업을 해보았다.

텔레그램에서> 버튼을 만들고 > 눌르면 > 네이버뉴스를 실시간 크롤링 해와서 > 텔레그램방에 뿌려주기

 

먼저 웹크롤링 하는 부분

import requests
from bs4 import BeautifulSoup

def get_news()-> None:
    # 크롤링할 URL 설정

    # 해당 URL로 HTTP GET 요청 보내고 응답을 받음
    response = requests.get(url)

    # HTTP 요청이 성공적으로 이루어졌는지 확인
    if response.status_code == 200:
        # BeautifulSoup을 사용하여 HTML 파싱
        soup = BeautifulSoup(response.text, 'html.parser')
       
        # 뉴스 기사 제목과 링크를 추출
        news_articles = soup.find_all('dd', class_='articleSubject')
        # print(news_articles)

        rtn_str = ""
        for article in news_articles:
            title = article.find('a').text
            link = 'https://finance.naver.com' + article.find('a')['href']

            rtn_str += f'제목: {title}'
            rtn_str += "\n"
            rtn_str += f'링크: {link}'
            rtn_str += "\n"
            rtn_str += '-------------\n'
            # print(f'제목: {title}')
            # print(f'링크: {link}')
            # print('--------------------------')
            # print(rtn_str)
        return rtn_str
    else:
        print('HTTP 요청 실패')

if __name__ == "__main__":
    get_news()

 

 

임포트 해주고

import news_test as nt

버튼을 만들어 주고

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    keyboard = [    
        [
            InlineKeyboardButton("buy", callback_data="1"),
            InlineKeyboardButton("sell", callback_data="2"),
        ],
        [InlineKeyboardButton("감시", callback_data="3"),
         InlineKeyboardButton("실시간속보", callback_data="4")],
    ]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text(" Hi! My name is start Bot. I will hold a conversation with you. ", reply_markup=reply_markup)

버튼을 콜백을 받아 new_test.py파일을 호출

async def button(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Parses the CallbackQuery and updates the message text."""
    query = update.callback_query
    await query.answer()
   
    # logging.info(text=f"Selected option: {query.data}")
    # await query.edit_message_text(text=f"Selected option: {query.data}")
    if query.data == '1':
        # upbit.buycoin_mp("KRW-BTC", '10000')
        await query.edit_message_text("BTC-KRW  10000 W 매수합니다")
    elif query.data == '2':
        # upbit.sellcoin_mp("KRW-BTC")
        await query.edit_message_text("KRW-BTC 시장가 매도 합니다")
       
    elif query.data == '3':      
        await query.edit_message_text("BTC-KRW---start")
        await coin(update, context)

    elif query.data == '4':      
        await query.edit_message_text("naver증권-실시간속보를 가져옵니다")
        rtnVal = nt.get_news()  
        logging.info('--rtnVal='+ rtnVal)
        await query.edit_message_text(rtnVal)

버튼을 추가한 모습
크롤링을 성공한 모습

 

모바일 텔레그램에서 클릭하면 실제 모바일 네이버 뉴스로 이동된다.

끝~

+ Recent posts