tech

21/07/27 jupyter-notebook youtube data api 사용하여 youtube video id, playlist id 가져오기

tech-lover 2021. 7. 27. 13:06

- google api client 설치

$ sudo pip install --upgrade google-api-python-client

- 오류나는 경우

$ sudo pip install --upgrade google-api-python-client --use-feature=2020-resolver

 

 

 

## Examples

-- search video (검색어: 어벤져스)

 

```

# YouTube Data API (Search content)

req = youtube.search().list(part='snippet',

                            q='어벤져스',

                            type='video',

                            maxResults=50)

res = req.execute()

for item in res['items']:

    print( item['id']['videoId'], item['snippet']['publishedAt'], item['snippet']['title'])

```

 

-- 검색 목록 (정렬 결과)

```

## search oldest videos on a topic

from datetime import datetime

 

start_time = datetime(year=2018month=1day=1).strftime('%Y-%m-%dT%H:%M:%SZ')

end_time = datetime(year=2021month=1day=1).strftime('%Y-%m-%dT%H:%M:%SZ')

 

res = youtube.search().list(part='snippet',

                            q='파이썬 프로그래밍',

                            type='video',

                            publishedAfter=start_time,

                            publishedBefore=end_time,

                            maxResults=50).execute()

 

for item in sorted(res['items'], key=lambda x:x['snippet']['publishedAt']):

    print( item['id']['videoId'], item['snippet']['publishedAt'], item['snippet']['title'])

```

 

-- channel video id 가져오기

```

# Get all videos of a channel

def get_channel_videos(channel_id):

    

    # get Uploads playlist id

    res = youtube.channels().list(id=channel_id, 

                                  part='contentDetails').execute()

    playlist_id = res['items'][0]['contentDetails']['relatedPlaylists']['uploads']

    

    videos = []

    next_page_token = None

    

    while 1:

        res = youtube.playlistItems().list(playlistId=playlist_id, 

                                           part='snippet'

                                           maxResults=50,

                                           pageToken=next_page_token).execute()

        videos += res['items']

        next_page_token = res.get('nextPageToken')

    

        if next_page_token is None:

            break

    

    return videos

 

videos = get_channel_videos('UCp1R0TBvgM7gj0rwTYULmSA'## AlvinBlox

 

print("All videos ("str(len(videos)) + ") :")

i=0

for video in videos:

    i= i+1

    print(video['snippet']['publishedAt']+" id= "+ video['snippet']['resourceId']['videoId']+" "+video['snippet']['title']+" ")

```

 

 

-- playlist 가져오기

```

# get Uploads playlist id

def get_playlists(channel_id):

       

    videos = []

    next_page_token = None

    

    while 1:

        res = youtube.playlists().list(channelId=channel_id, 

                                           part='snippet'

                                           maxResults=50,

                                           pageToken=next_page_token).execute()

        videos += res['items']

        next_page_token = res.get('nextPageToken')

        

        if next_page_token is None:

            break

    

    return videos

 

videos = get_playlists('UCp1R0TBvgM7gj0rwTYULmSA'## AlvinBlox

 

print("Playlist :")

i=0

for video in videos:

    i= i+1

    print(str(i).zfill(2)+" "+video['id'])

```

 

-- playlist별로 video item 가져오기

```

# get Uploads playlist id

def get_playlists(channel_id):

       

    playlists = []

    next_page_token = None

    

    while 1:

        res = youtube.playlists().list(channelId=channel_id, 

                                           part='snippet'

                                           maxResults=50,

                                           pageToken=next_page_token).execute()

        playlists += res['items']

        next_page_token = res.get('nextPageToken')

        

        if next_page_token is None:

            break

    

    return playlists



# Get all videos of a playlist

def get_playlist_videos(playlist_id):

 

    videos = []

    next_page_token = None

    

    while 1:

        res = youtube.playlistItems().list(playlistId=playlist_id, 

                                           part='snippet'

                                           maxResults=50,

                                           pageToken=next_page_token).execute()

        videos += res['items']

        next_page_token = res.get('nextPageToken')

        

        if next_page_token is None:

            break

    

    return videos



playlists = get_playlists('UCp1R0TBvgM7gj0rwTYULmSA'## AlvinBlox

 

playlistsVideos = []

print("Playlist :")

for items in playlists:

    #print(listId['snippet']['title'])

    playlistsVideos += get_playlist_videos(items['id'])

 

    print(items['id'] +"\n"+items['snippet']['title']+"Videos ("str(len(playlistsVideos)) + ") :")

    

    for video in playlistsVideos:

        print(video['snippet']['publishedAt']+" id= "+ video['snippet']['resourceId']['videoId']+" "+video['snippet']['title']+" ")

```

 

 

References

- Google API Documentation

https://developers.google.cn/youtube/v3/getting-started?hl=ko 

 

시작하기  |  YouTube Data API  |  Google Developers

소개 이 문서는 YouTube와 상호작용할 수 있는 애플리케이션을 개발하려는 개발자를 위해 작성되었습니다. 여기에서는 YouTube 및 API의 기본 개념에 대해 설명합니다. 또한 API가 지원하는 다양한 기

developers.google.cn

 

- Youtube Data Api - Jupyter Notebook 사용하기

https://youtube.com/playlist?list=PLyb_C2HpOQSBJRh38CTPvsouV4SBpyt_H 

 

Exploring YouTube Data API - YouTube

 

www.youtube.com

- source code : https://github.com/nikhilkumarsingh/YouTubeAPI-Examples

 

GitHub - nikhilkumarsingh/YouTubeAPI-Examples: YouTube Data API Usage Examples using Python.

YouTube Data API Usage Examples using Python. Contribute to nikhilkumarsingh/YouTubeAPI-Examples development by creating an account on GitHub.

github.com

- Youtube API 개발 이야기

https://brunch.co.kr/brunchbook/youtubeapi 

 

[브런치북] 유튜브 API 개발 이야기

바야흐로 구독의 시대다. 온라인 세상의 흐름은 SNS에서 동영상으로 넘어가고 있고 그 중심에는 유튜브가 있다. 방송과 관련된 서비스를 개발하고 운영하다 보니, 새삼 유튜브가 대단하다는 생

brunch.co.kr

 

- jupyter-notebook 실행하기 (ide.goorm.io 사용)

https://tech5g.tistory.com/292

 

21/07/26 ide.goorm.io jupyter-notebook 실행하기

 

tech5g.tistory.com

- https://github.com/youtube/api-samples/tree/master/python

 

GitHub - youtube/api-samples: Code samples for YouTube APIs, including the YouTube Data API, YouTube Analytics API, and YouTube

Code samples for YouTube APIs, including the YouTube Data API, YouTube Analytics API, and YouTube Live Streaming API. The repo contains language-specific directories that contain the samples. - Git...

github.com