본문 바로가기
Python

파이썬 크롤링 requests, BeautifulSoup 네이버 영화 관람객 리플 데이터 수집

by wanttosleep1111 2023. 1. 19.

파이썬 크롤링 requests, BeautifulSoup 네이버 영화 관람객 리플 데이터 수집

 

▶ 목표

 

  • 네이버 영화 > 영웅 > 평점 > 관람객 리플 데이터 수집
  • 관람객 리플 데이터 10페이지까지 모으기
  • 10페이지까지 모은 데이터를 파일 쓰기/읽기 함수를 통해 텍스트 파일로 저장해보기
  • 리플 데이터를 워드클라우드로 그려보기

 

① 평점 탭에 있는 리플 데이터 접근하기

※ 네이버 영화의 평점 탭에 있는 리플 데이터는 iframe module로 하나의 html 문서 안에 또다른 html 문서가 있는 구조

개발자 도구로  리플 html의 주소를 확인해 들어가서 태그 위치 확인

 

② 리플 데이터를 불러오고 출력하기

※ 파일 쓰기, 읽기

  • 쓰기
    f = open('경로및파일명', '쓰기모드')
    f.write('')
    f.close()
  • 읽기
    f = open('./test.txt', 'r')
    data = f.readline()
    f.close()
  • with 이용
    with open('./test.txt', 'r') as f:
        data = f.readline()
# 1.for문을 사용해서서 1~10번 페이지 접근하기 
f = open('./review.txt','w') # 파일 쓰기 열기
for i in range(1,11):
    url = 'https://movie.naver.com/movie/bi/mi/pointWriteFormList.naver?code=184509&type=after&isActualPointWriteExecute=false&isMileageSubscriptionAlready=false&isMileageSubscriptionReject=false'
    res = req.get(url, headers = header, params={'page': i})
#     print(res.url)
    # 객체 변환 
    html = bs(res.text, 'lxml')
    # 리뷰 문장 추출
    reple = html.select('.score_reple > p > span:nth-child(2)') # list, 10개요소    
    # for 문 돌리며 text만 추출 후 출력 
    for j in range(len(reple)): # 0 ~ 9 
        f.write(reple[j].text.strip()) # 파일 쓰기
        
f.close() #파일 객체 종료
# review.txt 읽어보기
f = open('./review.txt','r')
data = f.readline()
f.close()

 

 

# 파일 다루기 응용
# 자동적으로 문장을 수행하고 난 후 파일 객체를 닫아줌(종료)
with open('./review.txt', 'r') as f:
    data = f.readline()
print(data)

 

③ 워드클라우드 그린 후, jpg파일로 저장

  • matplotlib, wordcloud 라이브러리 필요
# 워드 클라우드 설치
!pip install wordcloud
from wordcloud import WordCloud 
# 빈도수가 높은 단어를 크게 표현하거나 낮은 단어를 작게 표현
# 스타일 지정
import matplotlib.pyplot as plt
# 워드클라우드 사용
# 폰트 : 맑은 고딕
# 배경 : white
# 컬러맵 : Dark2
wc = WordCloud(font_path = "C:/Windows/Fonts/malgunbd.ttf",
              background_color = 'white',
              colormap = 'Dark2').generate(data)
              
# matplotlib를 이용해 figure 크기, 축 설정 후 jpg 파일로 저장하기
plt.figure(figsize=(12,5)) # 워드 클라우드 크기 설정
plt.axis('off')
plt.imshow(wc)
plt.savefig('./워드클라우드결과.jpg') # 이미지로 저장

댓글