본문 바로가기
공부/파이썬 Python

에브리타임 크롤링 & 워드클라우드 하는 방법

by 혼밥맨 2022. 4. 5.
반응형

에브리타임 크롤링 & 워드클라우드 하는 방법

에브리타임

에브리타임은 전국 400개 대학을 지원하는 대학교 커뮤니티 및 시간표 서비스. 시간표 작성 및 학업 관리, 학교 생활 정보, 학교별 익명 커뮤니티 기능을 제공합니다.

 

워드클라우드 (Word Cloud)

워드 클라우드란 문서의 키워드, 개념 등을 직관적으로 파악할 수 있도록 핵심 단어를 시각화하는 기법이다. 예를 들면 많이 언급될수록 단어를 크게 표현해 한눈에 들어올 수 있게 하는 기법 등이 있다. 주로 빅데이터(big data)를 분석할 때 데이터의 특징을 도출하기 위해 활용한다.

개발환경

Google Colab 구글 코랩.  Colaboratory를 줄여서 일반적으로 Colab이라고 부르며, 한국에서는 코랩이라고 한다. Colab은 구글에서 만든 연구용 서비스 제품이며, Jupyter를 기반으로 만들어진 웹용 서비스이다.

폰트

malgun.ttf

다운로드 링크: https://www.wfonts.com/font/malgun-gothic

 

Download Free Font Malgun Gothic

Malgun GothicBoldMalgun Gothic BoldMalgun Gothic BoldVersion 6. 50MalgunGothicBoldMalgun Gothic is a trademark of the Microsoft group of companies. Microsoft CorporationKyoung-bae Lee; Daekwon KimMalgun Gothic is a Korean font developed by taking advantage

www.wfonts.com

파이썬에서 제공되는 WordCloud 라이브러리는 워드클라우드 자체를 제공하지만 한글 폰트는 제공하지 않는다. 그래서 한글 폰트를 자신의 디렉토리에 반드시 저장해야 한다. (워드클라우드를 한글로 만들고 싶다면)

라이브러리 설치

1
2
3
4
5
!pip install krwordrank
!apt-get update
!apt install chromium-chromedriver
!pip install selenium
!cp /usr/lib/chromium-browser/chromedriver /usr/bin
cs

폰트 업로드

에브리타임 로그인

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from selenium import webdriver
from time import sleep
import random
 
webdriver_options = webdriver.ChromeOptions()
webdriver_options.add_argument('--headless')
webdriver_options.add_argument('--no-sandbox')
webdriver_options.add_argument('--disable-dev-shm-usage')
webdriver_options.add_argument('user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36')
 
driver = webdriver.Chrome('chromedriver', options=webdriver_options)
driver.implicitly_wait(1)
 
# ID & PW
id = 'YourID'
pw = 'YourPassword'
 
# 로그인 페이지에서 로그인하기
url = 'https://everytime.kr/login'
driver.get(url)
driver.find_element_by_name('userid').send_keys(id)       # ID 입력
driver.find_element_by_name('password').send_keys(pw)     # PW 입력
driver.find_element_by_xpath('//*[@id="container"]/form/p[3]/input').click() # 로그인 버튼 클릭
driver.implicitly_wait(20)                                   # 로그인 후 페이지가 로드될 때까지 
cs

크롤링

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# 글, 댓글을 저장하는 리스트
results = []
 
cnt = 0         # 시작 페이지
max_cnt = 50    # 마지막 페이지
 
 
while True:
  print('Page ' + str(cnt))
 
  if cnt > max_cnt: # 페이지 설정
    break;
  
  cnt = cnt + 1
  driver.get('https://everytime.kr/{$ 학교 고유의 자유게시판 번호}/p/' + str(cnt))
  driver.implicitly_wait(50)
 
  posts = driver.find_elements_by_css_selector('article > a.article')
  links = [post.get_attribute('href'for post in posts]
 
  for link in links:
    driver.implicitly_wait(50)
    
    # 1-6초 사이 랜덤 n초 만큼 sleep
    # 에브리타임은 크롤링 봇을 강력히 금지하기 때문에 sleep을 반드시 써야함!
    # 에브리타임에서는 크롤링 의심되는 계정은 '영구정지'함
    sleep(random.randrange(1,7))
    driver.get(link)
 
    #게시글, 댓글 크롤링
    comments = driver.find_elements_by_css_selector('p.large')
 
    for comment in comments:
      results.append(comment.text)
 
 
# 리스트를 하나의 문자열로 변환
long_results = ' '.join([str(result) for result in results])
print(long_results)
 
 
# Visualizing Word Cloud
from wordcloud import WordCloud
import numpy as np
import matplotlib.pyplot as plt
import PIL.Image
 
wc = WordCloud(font_path='/content/malgun.ttf').generate(long_results)
 
plt.imshow(wc)
plt.axis("off")         # 워드클라우드 이미지 축 제거
plt.show()                # 워드클라우드 이미지 띄우기
cs

print(long_results)

워드클라우드 결과

 

반응형

댓글