기존에 구글에서 서치해서 찾아볼 수 있는 스마트스토어 리뷰 스크래핑 코드에서 일부 수정한 코드입니다. 데모데이 프로젝트를 위해 바늘이야기 네이버 스마트 스토어에 등록되어 있는 제품들의 리뷰를 스크래핑해 텍스트 분석을 해보려고 합니다.
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time, random, datetime
import pandas as pd
def chromeWebdriver():
chrome_service = ChromeService(executable_path=ChromeDriverManager().install())
options = Options()
options.add_experimental_option('detach', True)
options.add_experimental_option('excludeSwitches', ['enable-logging'])
user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36'
options.add_argument(f'user-agent={user_agent}')
driver = webdriver.Chrome(service=chrome_service, options=options)
return driver
url ='https://smartstore.naver.com/danchoo/products/4454697133'
driver = chromeWebdriver()
driver.implicitly_wait(5)
driver.get(url)
cnt = 1
review = []
for page in range(1, 371//20+3):
time.sleep(2)
lis = driver.find_element(By.XPATH, f'//*[@id="REVIEW"]/div/div[3]/div[2]/ul').find_elements(By.TAG_NAME, 'li')
for li in lis:
review.append(li.text.split('\n')) # '\n'을 기준으로 문자열 나누어서 리스트 각각의 원소로 만들기
cnt += 1
time.sleep(random.uniform(2, 4))
driver.find_element(By.CSS_SELECTOR, '#REVIEW > div > div._180GG7_7yx > div.cv6id6JEkg > div > div > a.fAUKm1ewwo._2Ar8-aEUTq').click()
driver.implicitly_wait(7)
driver.quit()
리뷰 페이지 수
//20+3):리뷰가 존재하는 코드의 XPATH
).find_elements(By.TAG_NAME, 'li')다음 버튼 코드의 selector
).click()//*[@id="REVIEW"]/div/div[3]/div[2]/div/div/a[8]
)인데 '다음'을 누르고 나면//[@id="REVIEW"]/div/div[3]/div[2]/div/div/a[9]
)로 변경이 되어 8이 부여된 리뷰 7페이지가 중복되어 나오는 것을 확인할 수 있습니다.df = pd.DataFrame(review)
df
스크래핑 완료!
df.to_csv('버터 6 리뷰.txt',sep='\t', index=False)
저장할 파일 이름
.txt', sep='\t', index=False)sep = '\t'
: tab키가 적용된 부분 기준으로 열을 나눠 줌index = False
: 인덱스 붙여지면 헷갈릴까봐 붙여주지 않음(붙이고 싶으면 True로 변경)주의할 점: 첫 페이지의 리뷰 20개가 중복으로 나온다. 그래서 나는 따로 앞 20개의 리뷰만 직접 지워주는 작업을 했다.