분석 목적
블로그 리뷰 데이터를 수집하여 소비자 의견과 트렌드를 분석하고, 이를 통해 제품 및 서비스 개선에 대한 인사이트를 도출하기 위함
크롤링
위의 사진은 네이버 플레이스의 카페 리뷰 사진이며, ID, 리뷰 수, 사진 수, 팔로워 수, 리뷰, 코멘트, 별점, 날짜, 그리고 방문 횟수가 나와 있습니다. Selenium과 Beautiful Soup을 활용하여 이 데이터를 수집하겠습니다
Selenium과 Beautiful Soup(리뷰)
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
import time
chrome_options=webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
driver=webdriver.Chrome('chromedriver', chrome_options=chrome_options)
driver.get('url')
웹 핸들링 크롬 드라이브 환경 설정 → 드라이브를 통한 URL 접근 → 데이터 수집
정적 데이터 수집(단순 자료 수집)은 Beautiful Soup을 활용하고, 동적 데이터 수집(스크롤 내리기, 클릭, 로그인 등 웹 상의 동작이 필요한 경우)은 Selenium을 사용합니다.
##댓글 긁어 모으기
review=[] ## 댓글 내용 리스트
prev_height = driver.execute_script("return document.body.scrollHeight") ### 현재 문서 높이를 가져와서 저장
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
##스크롤 끝까지 내림
# 페이지 로딩 대기
time.sleep(5)
# 현재 문서 높이를 가져와서 저장
curr_height = driver.execute_script("return document.body.scrollHeight")
if curr_height == prev_height:
break
else:
prev_height = curr_height
html=driver.page_source ##홈페이지의 html 소스 가져오기
soup=BeautifulSoup(html, 'html.parser') ##파싱 준비
review_items=soup.find_all('span',{'class':'_7nYoZ'}) ##파싱
for r_item in review_items:
print(r_item.text)
review.append(r_item.text) ## 텍스트 저장
driver.quit()
해당 부분의 데이터를 수집하기 위해 스크롤에 유의하며 파싱합니다. Selenium을 활용하여 스크롤을 조정한 후, 정적 데이터를 수집합니다. 크롤링할 HTML 태그를 찾아 파싱합니다.
개발자 도구를 활용하여 HTML 태그를 찾습니다. 태그를 찾은 후, find_all 함수를 이용해 모든 댓글을 수집합니다.
Selenium과 Beautiful Soup(코멘트와 버튼 클릭)
prev_height = driver.execute_script("return document.body.scrollHeight") ### 현재 문서 높이를 가져와서 저장
while True:
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
##스크롤 끝까지 내림
# 페이지 로딩 대기
time.sleep(2)
# 현재 문서 높이를 가져와서 저장
curr_height = driver.execute_script("return document.body.scrollHeight")
if curr_height == prev_height:
break
else:
prev_height = curr_height
comment=[]
for comment_button in range(500):
try:
buttons=driver.find_elements(By.CLASS_NAME,'_11i38')
buttons[comment_button].click()
except:
print('buttons{}_click x'.format(comment_button))
pass
##review_items=soup.find_all('span',{'class':'_7nYoZ'}) ##파싱
html=driver.page_source
soup=BeautifulSoup(html, 'html.parser')
comment_items=soup.find_all('span', {'class':'_11i38'})
for c_item in comment_items:
print(c_item.text)
comment.append(c_item.text)
driver.quit()
+4 부분의 버튼클릭 부분에 유의하여 데이터를 수집합니다.
버튼을 클릭해야 코멘트가 모두 등장하므로, Selenium을 활용하여 버튼 경로를 찾고, 코멘트에 있는 모든 버튼을 클릭합니다.
HTML 버튼 태그와 클래스를 파악한 후, find_elements 함수를 이용해 버튼을 찾고 click() 함수를 사용하여 버튼을 클릭해야 합니다.
데이터를 수집한 후, 데이터 전처리를 통해 분석 데이터 프레임을 만들었습니다.
'Analysis Report > 네이버 리뷰 분석' 카테고리의 다른 글
네이버 리뷰 분석(분석 보고서) (0) | 2022.11.17 |
---|