사용 URL : https://youtube-rank.com/board/bbs/board.php?bo_table=youtube
from selenium import webdriver
from bs4 import BeautifulSoup
browser = webdriver.Chrome('c:/webdriver/chromedriver.exe') # 크롬 시작
result = []
for page in range(1, 11):
url = f"https://youtube-rank.com/board/bbs/board.php?bo_table=youtube&page={page}" # url 동적으로 변환
browser.get(url)
time.sleep(2) # 2초 기다려서 서버 부담 감소
html = browser.page_source
soup = BeautifulSoup(html, 'html.parser')
channel_list = soup.select('form > table > tbody > tr') # 조건을 구체적으로 해서 필요한 정보만 수집
for channel in channel_list:
title = channel.select('h1 > a')[0].text.strip()
category = channel.select('p.category')[0].text.strip()
subscriber = channel.select('.subscriber_cnt')[0].text
view = channel.select('.view_cnt')[0].text
video = channel.select('.video_cnt')[0].text
data = [title, category, subscriber, view, video]
result.append(data)
df = pd.DataFrame(result)
df.columns = ['title','category','subscriber','view','video']
df.to_excel('./files/youtube_rank.xlsx',index = False)
데이터 수집 코드를 작성하던 도중 책과 다른 부분이 있어서 책과 비교 실험 진행
channel_list = soup.select('tbody > tr') # 책의 코드
channel_list = soup.select('form > table > tbody > tr') # 수정한 코드
조건으로 부모 태그들을 추가해서 해결
matplotlib으로 차트를 그리면 한글이 깨진다고 한다.
이는 책에 나와 있던 아래 코드로 해결 가능했다.
from matplotlib import font_manager, rc
import platform
if platform.system() == 'Windows': # 운영체제가 Windows일 때
path = 'c:/Windows/Fonts/malgun.ttf'
font_name = font_manager.FontProperties(fname = path).get_name()
rc('font', family = font_name)
elif platform.system() == 'Darwin': # 운영체제가 macOS일 때
rc('font', family = 'AppleGothic')
else:
print('Check your OS system')
수집한 부분에서 구독자 수는 '~만'으로 문자열 값으로 되어있다.
이를 숫자 데이터로 변환을 먼저 시켜준다.
df['replaced_subscriber'] = df['subscriber'].str.replace('만', '0000').astype('int')
시각화는 카테고리별 구독자 수, 채널 수로 진행하여 이를 피벗 테이블로 만들었다.
pivot_df = df.pivot_table(values = 'replaced_subscriber',
index = 'category',
aggfunc = ['sum','count']) # 두 개의 값을 동시에 얻는다
pivot_df.columns = ['subscriber_sum','category_count'] # 칼럼명을 변경
pivot_df = pivot_df.reset_index() # subscriber_sum과 category_count는 인덱스로 설정이 되어있는데 이것을 초기화 시켜 series로 변경시켜 준다
pivot_df = pivot_df.sort_values(by='subscriber_sum', ascending=False) # subscriber_sum으로 내림차순 정렬, ascending을 비워두면 오름차순
카테고리별 구독자 수 시각화
plt.figure(figsize = (30,10)) # 차트의 크기 설정, x, y축을 각각 30, 10으로 설정
plt.pie(pivot_df['subscriber_sum'], labels=pivot_df['category'], autopct='%1.1f%%') # %1.1ff%%는 수치 값을 소수점 한 자리까지 퍼센트로 표시하라는 뜻
plt.show()
카테고리별 채널 수 시각화 하기
pivot_df = pivot_df.sort_values(by='category_count', ascending=False) # 카테고리별 채널 수로 시각화하기 때문에 데이터를 다시 채널 수로 내림차순 정렬
plt.figure(figsize = (30, 10))
plt.pie(pivot_df['category_count'], labels=pivot_df['category'],autopct='%1.1f%%')
plt.show()