Python을 활용한 Youtube Livestream comments 추출 코드
구글클라우드 계정 생성 후 무료 크레딧 사용
Window환경에서 작업
# yotube data API v3 - API Key
# AIzaSyClPVR9idoaAoaCZ********pLpR9WJAQ
import pytchat
from pytchat import LiveChat
import pafy
import pandas as pd
pafy.set_api_key('AIzaSyClPVR9i********aCZKCU1dfwpnpLpR9WJAQ')
# AI챌린지
# video_id = 'Vwp2uU2sYEI'
video_id = '82azTKMt2K4'
v = pafy.new(video_id)
title = v.title
author = v.author
published = v.published
print(title)
print(author)
print(published)
empty_frame = pd.DataFrame(columns=['제목', '채널 명', '스트리밍 시작 시간', '댓글 작성자', '댓글 내용', '댓글 작성 시간'])
empty_frame.to_csv('./youtube.csv')
chat = pytchat.create(video_id= video_id)
while chat.is_alive():
cnt = 0
# print(cnt)
try:
data = chat.get()
items = data.items
# print("items : ",items)
for c in items:
# print("for진입해?")
print(f"{c.datetime} [{c.author.name}]- {c.message}")
data.tick()
data2 = {'제목' : [title], '채널 명' : [author], '스트리밍 시작 시간' : [published], '댓글 작성자' : [c.author.name], '댓글 내용' : [c.datetime], '댓글 작성 시간' : [c.message]}
result = pd.DataFrame(data2)
result.to_csv('youtube.csv', mode='a', header=False, encoding='euc-kr')
cnt += 1
if cnt == 5 : break
except KeyboardInterrupt:
chat.terminate()
break