[python] Selenium과 Beautifulsoup를 활용한 유튜브 댓글 크롤링

Jihyun·2023년 12월 6일
1

< 유튜브 댓글 수집 >

유튜브 댓글을 수집하는 방법은 크게 2가지입니다. 첫번째는 Google에서 제공하는 유튜브 API를 사용하는 것이고, 두번째는 직접 HTML문서에서 크롤링하는 방법이 있습니다. 하지만 첫번째 방법은 할당량이 넘으면 API를 유료로 사용해야 해서 두번째 방법으로 진행해봤습니다.

Selenium과 BeatifulSoup를 사용해서 유튜브 댓글 크롤링을 진행해봤습니다.

1. 필요한 라이브러리 불러오기

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를 사용했습니다.

2. 크롤링할 유튜브 불러오기

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 주소 부분에 입력하면 됩니다.

  1. 웹페이지 끝까지 스크롤하기
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문서가 생깁니다. 따라서 모든 댓글을 수집하기 위해서는 웹페이지의 스크롤을 끝까지 내린 후에 크롤링하면 됩니다.

4. 유튜브 팝업 닫기

try:
    driver.find_element_by_css_selector("#dismiss-button > a").click()
except:
    pass

유튜브 프리미엄 팝업이 뜨는 것을 닫아주는 역할을 합니다. 팝업이 댓글을 크롤링할 때 방해가 될 수 있어 꼭 꺼주는 것이 좋습니다.

5. 대댓글 버튼 누르기

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()

유튜브 댓글은 댓글 뿐만 아니라 대댓글까지 존재합니다. 대댓글은 일반적으로 토글 형태로 저장되어 있어서 이 토글 버튼을 모두 눌러줘야 모든 댓글을 불러올 수 있습니다.

6. 댓글 가져오기

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) # 댓글 내용

유튜브 댓글 작성자와 댓글 내용을 가져옵니다. 댓글 내용만 필요하다면 댓글 작성자 부분은 제거해도 되겠죠?

7. 댓글 저장하기

pd_data = {"아이디" : id_final , "댓글 내용" : comment_final}
youtube_pd = pd.DataFrame(pd_data)

youtube_pd.to_excel('result.xlsx')

마지막으로 크롤링한 결과를 {아이디, 댓글내용}의 형태로 엑셀 파일에 저장합니다.


  • 제안: 코드를 한 번에 Run하면 댓글이 저장되지 않는 것을 확인할 수 있었습니다. selenium은 사람이 스크롤하고 대댓글 버튼을 누르는 것처럼 점진적으로 진행됩니다. 즉, 코드를 한 번에 돌려버리면 스크롤을 끝까지 진행하지 못하거나 대댓글 버튼을 모두 누르지 못한 채 저장됩니다. 따라서, 1번부터 5번 코드까지 돌린 후에 웹페이지의 스크롤과 대댓글 버튼 누르는 작업이 모두 완료된 것을 확인한 후에 댓글을 저장하는 것을 추천드립니다!
profile
혼자 공부하는 데이터분석

0개의 댓글