우선 데이터 수집 방법이다.
from selenium import webdriver
webdriver라는 API를 통해 운영체제에 설치된 Chrome등의 브라우저를 제어할 수 있다.
#인기동영상 url 크롤링
url = 'https://www.youtube.com/feed/trending'
driver = webdriver.Chrome("/Users/joseongju/Downloads/chromedriver 4")
driver.maximize_window()
url = "https://www.youtube.com/feed/trending"
driver.get(url)
tm.sleep(40)
# 인기동영상 url
url = []
for video_tag in driver.find_elements(By.CSS_SELECTOR,"#video-title"):
url.append(video_tag.get_attribute("href")) # url 추출
# 인기급상승동영상 재생시간
time = []
for video_time in driver.find_elements(By.CSS_SELECTOR,"#overlays > ytd-thumbnail-overlay-time-status-renderer > span"):
time.append(video_time.get_attribute("aria-label")) # 영상 시간 추출
driver.close()
driver을 통해 유튜브 인기동영상 페이지에 접속하며 각 영상의 url과 영상 시간을 추출한다.
#url, 영상재생시간 df화
df = pd.DataFrame(url)
df['time'] = time
df = df[df.time != 'Shorts'] #shorts는 제외
df.rename(columns = {0:'url'},inplace = True)
# = 앞 url 전체 제거시 ? 문자로 인한 오류로 3번에 나누어 전처리
df['url'] = df['url'].str.replace('https://www.youtube.com/watch','')
df['url'] = df['url'].str.replace('?','')
df['url'] = df['url'].str.replace('v=','')
#index 재배열
df.reset_index(inplace=True, drop=False)
#기존 index 삭제
df.drop('index', axis=1)
shorts 영상은 제외하였으며 추출한 결과값들을 dataframe으로 만들어줬다.
https://www.youtube.com/watch?v=6RQ-bBdASvk 에서 동영상 고유키는 6RQ-bBdASv인데 각 영상의 url에서 동영상 고유키들만이 필요한 것이었기에 = 앞 모든 문자들은 제거해주었다.
DEVELOPER_KEY = '' # 유튜브 api값
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=DEVELOPER_KEY)
발급받은 api값을 DVELOPER_KEY에 넣어주고 youtube 변수에 값을 저장해주었다.
ids = [] #동영상 id
titles = [] #동영상 제목
channeltitle = [] #채널 이름
category_ids = [] #동영상 카테고리 id
dates = [] #동영상 업로드 날짜
views = [] #조회수
like = [] #좋아요
comments = [] #댓글 수
description = [] # 영상 설명
time = [] #영상 길이
# youtube api 태그를 통해 데이터 추출
for i in range(len(df)):
request = youtube.videos().list(
id = df['url'][i], #영상 id 입력
part = 'snippet,contentDetails,statistics'
)
response = request.execute()
if response['items'] == []:
titles.append('-')
ids.append('-')
dates.append('-')
category_ids.append('-')
views.append('-')
comments.append('-')
time.append('-')
channeltitle.append('-')
description.append('-')
like.append('-')
else:
titles.append(response['items'][0]['snippet']['title'])
ids.append(df['url'][i])
dates.append(response['items'][0]['snippet']['publishedAt'])
category_ids.append(response['items'][0]['snippet']['categoryId'])
views.append(response['items'][0]['statistics']['viewCount'])
try:
like.append(response['items'][0]['statistics']['likeCount'])
except KeyError as l:
like.append(0)
try:
comments.append(response['items'][0]['statistics']['commentCount'])
except KeyError as l:
comments.append(0)
channeltitle.append(response['items'][0]['snippet']['channelTitle'])
description.append(response['items'][0]['snippet']['description'])
time.append(df['time'][i])
detail_df = pd.DataFrame([ids, titles, channeltitle, category_ids, dates, views, like, comments, description, time]).T
detail_df.columns = ['video_id','title','channel_title','category_id','publish_time', 'views', 'likes', 'comment_count', 'description', 'time']
#api로 얻을 수 있는 인기동영상 데이터
detail_df
이후 동영상 제목, 조회수, 좋아요 수 등의 변수를 뽑아왔다. 앞서 dataframe으로 정리해둔 동영상 고유키값을 활용하여 변수들을 가져올 수 있었다.
데이터 수집은 이와같은 방식으로 22년 7~8월간 수집하였다.
이후 글에서는 kaggle에서 얻을 수 있는 17년 ~ 18년도 데이터를 분석해보고 이를 직접 수집한 22년 데이터와 비교해보며 변화된 영상 소비 트렌드를 분석해볼 예정이다.
'python' 카테고리의 다른 글
유튜브 트렌드 비교 분석 - 데이터 분석편 (2) | 2023.01.08 |
---|---|
HR데이터를 활용한 퇴직자 예측 모델 (1) | 2023.01.06 |
지하철 장애인 시위에 대한 유튜브 댓글 분석 (1) | 2023.01.05 |