[Python] Youtube 동영상 게시물 댓글 추출

강우용·2024년 7월 17일

Python을 활용한 Youtube 동영상 게시물 댓글 추출 코드

구글클라우드 계정 생성 후 무료 크레딧 사용

Window환경에서 작업

주의!!
실행해보면 Error: pytchat.core.multithread.livechat:internal exception - <class 'RuntimeError'> Cannot open a client instance more than one.

이란 문구가 터미널에 찍힐 것이다. RuntimeError는 말 그대로..실행중 에러이므로 작동이 멈춰야 정상이지만... 잘 작동하고 있는거다. 라이브챗에서 채팅이 쳐지면 잘 프린트되는 것을 볼 수 있다. 이 오류를 찾기위해 2시간 뻘짓을 하다 우연히 라이브채팅을 치다 알게된 사실.. 다들 주의 하길 바람.



# yotube data API v3 - API Key 
# AIzaSyClPVR9idoaAoaCZKCU1dfwpnpLpR9WJAQ

import pytchat
from pytchat import LiveChat
import pafy
import pandas as pd
import pytchat

pafy.set_api_key('AIzaSyClPVR9idoaAoaCZKCU1dfwpnpLpR9WJAQ')

# AI챌린지
# video_id = 'Vwp2uU2sYEI'
video_id = '82azTKMt2K4'


class ChatClientSingleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        print("new진입")
        if not cls._instance:
            cls._instance = super(ChatClientSingleton, cls).__new__(cls, *args, **kwargs)
            cls._instance.chat = pytchat.LiveChat(video_id="82azTKMt2K4")  # Replace with your video ID
        return cls._instance

    def run(self):
        print("run 진입")
        chat = self.chat
        while chat.is_alive():
            try:
                print("chat.is_alive 진입은 하니?")
                data = chat.get()
                items = data.items
                print("items : ", items)
                for c in items:
                    print("아이템안으로 오긴해?")
                    print(f"{c.datetime} [{c.author.name}] - {c.message}")
                    # Process the chat data as needed
            except KeyboardInterrupt:
                chat.terminate()
                break

if __name__ == "__main__":
    # Example usage:
    client = ChatClientSingleton()
    client.run()
profile
I believe that if you spend 30 minutes every day taking a small step towards your dream, you will reach the dream someday.

0개의 댓글