작성
·
525
·
수정됨
0
URL : https://game.naver.com/lounge/Viking_Rise/board/detail/2583518
사용 코드
import requests
from bs4 import BeautifulSoup
import openpyxl
url = "https://game.naver.com/lounge/Viking_Rise/board/detail/2583518"
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, "html.parser")
comment_items = soup.select(".comment_item_text__1foPs")
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = "Crawled Comments"
sheet.cell(row=1, column=1, value="Comment Text")
sheet.cell(row=1, column=2, value="Attributes")
for index, comment_content in enumerate(comment_items, start=2):
comment_text = comment_content.get_text(strip=True)
comment_attributes = str(comment_content.attrs)
sheet.cell(row=index, column=1, value=comment_text)
sheet.cell(row=index, column=2, value=comment_attributes)
workbook.save("crawled_comments.xlsx")
print("Comment attributes have been crawled and saved to crawled_comments.xlsx")
답변 1
0
안녕하세요, 인프런 AI 인턴이에요. 크롤링 코드가 막혀서 도움을 요청하신 거죠?
네이버 게임의 라운지에 있는 댓글들을 크롤링해보려고 하셨는데, 코드가 정상적으로 동작하지 않는다는 말씀이신 거죠.
먼저, 코드를 살펴보면 로직은 크게 문제가 없어보입니다. 그런데 해당 URL의 댓글은 JavaScript를 통해 동적으로 로딩되기 때문에, requests 라이브러리를 사용해서 HTML을 가져온다고 해도 원하는 결과를 얻을 수 없습니다.
댓글을 크롤링하기 위해서는 Selenium과 같은 웹 자동화 도구를 사용하는 것이 좋습니다. Selenium을 사용하면 JavaScript가 실행된 후의 결과를 가져올 수 있어 원하는 댓글 데이터를 얻을 수 있을 겁니다.
Selenium을 사용하여 코드를 수정해보세요. 아래는 예시 코드입니다.
from selenium import webdriver
from bs4 import BeautifulSoup
import openpyxl
url = "https://game.naver.com/lounge/Viking_Rise/board/detail/2583518"
# 웹드라이버 실행 (Chrome을 사용하는 경우)
driver = webdriver.Chrome("chromedriver 경로 입력")
# 해당 URL로 이동
driver.get(url)
# 댓글이 로딩될때까지 잠시 대기
driver.implicitly_wait(3)
# 현재 페이지의 HTML 가져오기
html = driver.page_source
# BeautifulSoup을 사용하여 HTML 파싱
soup = BeautifulSoup(html, "html.parser")
# 원하는 요소 추출
comment_items = soup.select(".comment_item_text__1foPs")
# 엑셀 파일 생성 및 시트 생성
workbook = openpyxl.Workbook()
sheet = workbook.active
sheet.title = "Crawled Comments"
# 데이터 저장
sheet.cell(row=1, column=1, value="Comment Text")
sheet.cell(row=1, column=2, value="Attributes")
for index, comment_content in enumerate(comment_items, start=2):
comment_text = comment_content.get_text(strip=True)
comment_attributes = str(comment_content.attrs)
sheet.cell(row=index, column=1, value=comment_text)
sheet.cell(row=index, column=2, value=comment_attributes)
# 엑셀 파일 저장
workbook.save("crawled_comments.xlsx")
print("Comment attributes have been crawled and saved to crawled_comments.xlsx")
이렇게 코드를 수정하고 실행해보세요. Selenium을 사용하면 웹 페이지의 동적인 요소들을 제어할 수 있기 때문에, 원하는 댓글 데이터를 크롤링할 수 있을 겁니다. 추가로 Selenium을 사용하기 위해 webdriver.Chrome()
의 인자로 자신이 사용하는 웹 드라이버의 경로를 입력해주셔야 합니다.
잘 동작하는지 확인 후 문제가 있으면 언제든지 물어보세요. 수고하세요!