유튜브 댓글을 수집하는 방법은 크게 2가지입니다. 첫번째는 Google에서 제공하는 유튜브 API를 사용하는 것이고, 두번째는 직접 HTML문서에서 크롤링하는 방법이 있습니다. 하지만 첫번째 방법은 할당량이 넘으면 API를 유료로 사용해야 해서 두번째 방법으로 진행해봤습니다.
Selenium과 BeatifulSoup를 사용해서 유튜브 댓글 크롤링을 진행해봤습니다.
from selenium import webdriver
import time
from openpyxl import Workbook
import pandas as pd
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import warnings
warnings.filterwarnings('ignore')
유튜브 댓글 크롤링을 위해 selenium과 BeautifulSoup를 사용했습니다. 그리고 크롤링한 댓글을 저장하기 위해 openpyxl과 pandas를 사용했습니다. 또한 에러가 중요하긴 하지만 성가시기 때문에 warnings를 사용했습니다.
wb = Workbook(write_only=True)
ws = wb.create_sheet()
driver = webdriver.Chrome("chromedriver.exe")
driver.get("URL 주소를 입력하세요")
driver.implicitly_wait(3)
time.sleep(1.5)
driver.execute_script("window.scrollTo(0, 800)")
time.sleep(3)
댓글을 크롤링하기 전, 댓글을 저장할 빈 엑셀 파일(ws)를 만들어줍니다.
Google colab을 사용했을 때
driver = webdriver.Chrome("chromedriver.exe")
이 코드가 안돌아가길래 Jupyter Notebook으로 진행했습니다. 에러가 나시는 분들은 자신의 Chrome 버전과 동일한 chromedriver을 설치해주시면 됩니다.
크롤링하고 싶은 유튜브 주소를 URL 주소 부분에 입력하면 됩니다.
last_height = driver.execute_script("return document.documentElement.scrollHeight")
while True:
driver.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
time.sleep(1.5)
new_height = driver.execute_script("return document.documentElement.scrollHeight")
if new_height == last_height:
break
last_height = new_height
time.sleep(1.5)
유튜브는 스크롤을 내릴 때마다 새로운 HTML문서가 생깁니다. 따라서 모든 댓글을 수집하기 위해서는 웹페이지의 스크롤을 끝까지 내린 후에 크롤링하면 됩니다.
try:
driver.find_element_by_css_selector("#dismiss-button > a").click()
except:
pass
유튜브 프리미엄 팝업이 뜨는 것을 닫아주는 역할을 합니다. 팝업이 댓글을 크롤링할 때 방해가 될 수 있어 꼭 꺼주는 것이 좋습니다.
buttons = driver.find_elements_by_css_selector("#more-replies > a")
time.sleep(1.5)
for button in buttons:
button.send_keys(Keys.ENTER)
time.sleep(1.5)
button.click()
유튜브 댓글은 댓글 뿐만 아니라 대댓글까지 존재합니다. 대댓글은 일반적으로 토글 형태로 저장되어 있어서 이 토글 버튼을 모두 눌러줘야 모든 댓글을 불러올 수 있습니다.
html_source = driver.page_source
soup = BeautifulSoup(html_source, 'html.parser')
id_list = soup.select("div#header-author > h3 > #author-text > span")
comment_list = soup.select("yt-formatted-string#content-text")
id_final = []
comment_final = []
for i in range(len(comment_list)):
temp_id = id_list[i].text
temp_id = temp_id.replace('\n', '')
temp_id = temp_id.replace('\t', '')
temp_id = temp_id.replace(' ', '')
id_final.append(temp_id) # 댓글 작성자
temp_comment = comment_list[i].text
temp_comment = temp_comment.replace('\n', '')
temp_comment = temp_comment.replace('\t', '')
temp_comment = temp_comment.replace(' ', '')
comment_final.append(temp_comment) # 댓글 내용
유튜브 댓글 작성자와 댓글 내용을 가져옵니다. 댓글 내용만 필요하다면 댓글 작성자 부분은 제거해도 되겠죠?
pd_data = {"아이디" : id_final , "댓글 내용" : comment_final}
youtube_pd = pd.DataFrame(pd_data)
youtube_pd.to_excel('result.xlsx')
마지막으로 크롤링한 결과를 {아이디, 댓글내용}의 형태로 엑셀 파일에 저장합니다.