from pytube import YouTube
import os
import json
def cln_txt(txt):
return txt.replace('-', '').replace(' ', '_').replace('/', '~').replace('(', '').replace(')', '').replace('|','').replace('\\', '')
def download_data(url, v_type='video/mp4', res=['1080p', '720p']):
crawl_result = {'url': url} # url 딕셔너리 생성
yt = YouTube(url) # 영상정보 저장
streams = yt.streams # 스트림
crawl_result['title'] = yt.title # 영상 제목
folder_name = cln_txt(yt.title) # 폴더이름
target_folder = os.path.join('data', folder_name) # 파일 경로
if not os.path.exists(target_folder): # 없으면 생성
os.makedirs(target_folder)
targets = list()
for item in streams: # streams엔
if item.resolution in res and item.mime_type == v_type: # mine_type = 해상도 가 res와 같으면 타겟에 추가
targets.append(item)
res_cache = {'1080p': False, '720p': False}
for target in targets: # 영상 info 저장 (학습시 해상도 mime 타입 fps 중요)
video_info = {'resolution': target.resolution,
'mime_type': target.mime_type,
'fps': target.fps}
vid_path = os.path.join(target_folder, target.resolution) # 해당 폴더, 해상도
if res_cache[target.resolution] == True: # 영상 받았으면 생략
continue
try:
os.mkdir(vid_path) # 안받았으면 path 생성
except FileExistsError:
pass
target.download(vid_path) # 다운로드
with open(os.path.join(vid_path, 'video_info.json'), 'w') as f:
json.dump(video_info, f) # 영상 정보 json으로 저장
captions = yt.caption_tracks # 영상정보 url caption
subt_folder = os.path.join(target_folder, 'subtitles') # caption 파일 생성
os.mkdir(subt_folder)
for caption in captions: # caption txt 파일로 저장
text = caption.generate_srt_captions()
with open(os.path.join(subt_folder, caption.code + '_' + cln_txt(caption.name) + '.txt'), 'w') as f:
f.write(text)
return yt.title, True
대량 크롤링시
url 은 watch?v = 고유번호 형태로 크롤링
키워드 검색시 query = 검색어 형태로 크롤링
if __name__ == "__main__":
url = "https://www.youtube.com/watch?v=Nd78J7E-4q4"
try:
title, is_ok = download_data(url)
except Exception as e:
print(str(e))
print(url)
print()
youtube api 사용시 편리하지만 (추적, 제한)
'파이썬 딥러닝 ai 스쿨 기초 > lecture10' 카테고리의 다른 글
lecture10 2교시 RNN 언어 모델링 (0) | 2021.04.08 |
---|---|
lecture10 1교시 RNN 기초 (0) | 2021.04.07 |