마케터의 기록/파이썬 공부 중

파이썬 셀레니움/뷰티풀수프로 유튜브 댓글 크롤링 하기

기록하는 마케터 2021. 4. 18. 17:02
반응형

파이썬 프로그래밍으로 업무 자동화 할 줄 아는 스마트한 퍼포먼스 마케터 되기 두번째 프로젝트!

 

파이썬 셀레니움과 뷰티풀수프로 유튜브 댓글을 자동 추출하는, 크롤링, 웹 스크래핑 코드를 작성해보았다. 

 

1. 사용한 라이브러리 목록

- 유튜브 댓글 크롤링을 하기 위해 셀레니움과 뷰티풀수프를 사용했다. 

- 크롤링 한 댓글을 엑셀 파일에 저장하기 위해서 openpyxl과 pandas를 사용했다. 

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

 

2. 엑셀 시트 생성, 댓글 추출할 유튜브 영상 띄우기

- 추출한 댓글을 저장해둘 엑셀 시트를 하나 생성해둔다.  

- driver.get("URL")의 URL에 댓글 추출할 유튜브 영상 주소를 기입한다.

wb = Workbook(write_only=True)
ws = wb.create_sheet()

driver = webdriver.Chrome()
driver.get("URL")
driver.implicitly_wait(3)

time.sleep(1.5)

driver.execute_script("window.scrollTo(0, 800)")
time.sleep(3)

 

3. 유튜브 댓글 페이지 끝까지 스크롤 하기

- 웹에 유튜브 영상 내 등록된 모든 댓글을 노출되게 만들기 위해 페이지를 끝까지 스크롤 한다.

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)

 

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. 유튜브 댓글 가져오기

- 유튜브 댓글을 작성한 사람의 아이디와, 작성한 댓글 내용 2가지로 구분하여 가져온다. 

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('youtube.xlsx')

 

8. 유튜브 댓글 크롤링 전체 코드 

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

wb = Workbook(write_only=True)
ws = wb.create_sheet()

driver = webdriver.Chrome()
driver.get("URL")
driver.implicitly_wait(3)

time.sleep(1.5)

driver.execute_script("window.scrollTo(0, 800)")
time.sleep(3)

# 페이지 끝까지 스크롤
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)

# 팝업 닫기
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()

time.sleep(1.5)

# 정보 추출하기
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('youtube.xlsx')

 

9. 추출한 유튜브 댓글 엑셀 파일 예시

- 아래와 같이 유튜브 댓글이 엑셀 파일에 저장된다.

반응형