1. 사용할 라이브러리 import
from selenium import webdriver
import time
import pandas as pd
from openpyxl import Workbook
from bs4 import BeautifulSoup
selenium : 크롤링할 때 웹 페이지를 자동화하고자 할 때 사용 (여기서는 스크롤을 내릴 때 사용)
pandas : 데이터 프레임 사용
openpyxl : 파일을 엑셀에 저장하기 위해 사용
bs4 : BeautifulSoup 로 원하는 부분을 크롤링할 때 사용
2. 엑셀 작업 준비
# 엑셀에 테이블 시트 생성
wb = Workbook(write_only=True)
ws = wb.create_sheet()
3. 스크롤 내리기
browser = webdriver.Chrome('/Users/leehyungseok/Downloads/chromedriver')
# 웹 사이트 열기
browser.get('영상주소')
# 잠깐 대기
time.sleep(5)
# 유튜브 댓글 크롤링할 때, 스크롤 내리는거 필수!
browser.execute_script("window.scrollTo(0, 800)")
# 잠깐 대기
time.sleep(5)
4. 크롤링
# 페이지 끝까지 스크롤
last_height = browser.execute_script("return document.documentElement.scrollHeight")
while True:
browser.execute_script("window.scrollTo(0, document.documentElement.scrollHeight);")
time.sleep(1.5)
new_height = browser.execute_script("return document.documentElement.scrollHeight")
if new_height == last_height:
break
last_height = new_height
time.sleep(1.5)
html_source = browser.page_source
soup = BeautifulSoup(html_source, 'html.parser')
# 영상 제목
title = soup.select_one('#container > h1 > yt-formatted-string').get_text()
# 아이디
id_list = soup.select("div#header-author > h3 > #author-text > span")
id_final = []
# 댓글 내용
comment_list = soup.select("yt-formatted-string#content-text")
comment_final = []
5. 토큰화
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)
6. 데이터 데이터 프레임에 저장
pd_data = {"아이디" : id_final , "댓글 내용" : comment_final}
youtube_pd = pd.DataFrame(pd_data)
7. 데이터 프레임을 엑셀에 저장
# 엑셀 파일을 바탕화면에 저장
youtube_pd.to_excel('/Users/leehyungseok/Desktop/%s.xlsx'%(title))
코드를 실행하면!!
바탕화면에 영상제목.xlsx 파일이 만들어져 있고, 들어가보면
크롤링된 댓글 데이터들이 정상적으로 저장되었다!!
했는데... 맥북을 초기화해서 그런가...
뭐 보니까 JVM DLL 이 없어서 그런 것 같은데..
그래서 찾아보니까 터미털 접속 후 vi ~/.zshrc 입력한 다음에
export JAVA_HOME=/Library/Java/JavaVirtualMachines/zulu-15.jdk/Contents/Home
export PATH=${PATH}:$JAVA_HOME/bin:
이렇게 수정하고 source ~/.zshrc 입력하면 끝!
이라고 나와있지만 끝은 무슨 절대 호락호락하지 않다.
그냥 똑같은 에러가 또 나왔다..
'캡스톤 > 자연어처리' 카테고리의 다른 글
[자연어처리] 댓글 데이터 전처리 (2) (0) | 2022.04.05 |
---|---|
[자연어처리] No module named 'konlpy' 에러 (0) | 2022.04.05 |
[자연어처리] 댓글 데이터 전처리 (1) (0) | 2022.04.04 |
[자연어처리] 댓글 데이터 엑셀에 저장하기 (0) | 2022.04.03 |
[자연어처리] 유튜브 API 를 사용해 영상 댓글 데이터 가져오기 (0) | 2022.04.03 |