YouTube video management with Python 3

This time, I will try to display a list of videos of my account on the console.

Development environment

Rough procedure

  1. Preparation of Google API
  2. Create a Python virtual environment
  3. Run Python

Reference URL

http://silver-shell.org/blog/?p=227 http://qiita.com/ottati/items/f7782bc834847470d4c8

Preparing Google APIs

Control is done in the Google API Console.

Project creation and certification

To use the Google API, you need to create a "project". Select "Library" from the left menu [https://console.developers.google.com/apis/library) and select the YouTube Data API. Select "Create Project". (There are other ways to create a "project") Create a project with a suitable name. Please refer to here to delete the project. 006.png

Authentication information

Select "Library" from the left menu, Select YouTube Data API. Enable the button next to "Youtube API Data v3". If you enable it, there will be a button called "Create Credentials", so click on it.

002.png

The same screen can also be displayed by selecting "Authentication Information"-> "Authentication Information"-> "Select with Wizard". 009.png

Add credentials to your project

"Determine the type of credentials required" to "YouTube Data API v3" "Place to call API" to "Web browser (Javascript)" Set "Type of data to be accessed" to "User data" Click "Required Credentials". 003.png

Create an OAuth 2.0 client

Give an appropriate name in English for identification. 004.png

The approved redirect URI is "http: // localhost: 8080 /" To (This part may change depending on the environment. It may be 8000 or 8090, and it may not work without the last "/".) 005.png

Download credentials

Click the "Download" button to download the json file that describes the settings to be used on Python. You can download it after completing the settings here, but the file name may be different from when you downloaded it here. (Same content except for the file name) (This time it was a file called client_id.json.) 007.png

Building a virtual environment for Python

Build a new Python virtual environment for operation in the terminal (command prompt for windows). This time I named it youtube.

command


conda create -n youtube python=3.5.3
#When creating with a set of Anaconda
# conda create -n youtube python=3.5.3 anaconda
#When checking the created environment
# conda info -e
# conda list -n youtube
#When deleting the created virtual environment
# conda remove -n youtube --all

Virtual environment activation

Subsequent work is performed in the virtual environment.

command


# Windows
activate youtube
#Deactivate
# deactivate

# Mac
source activate youtube
#Deactivate
# source deactivate

Django installation

cmd


conda install -c https://conda.anaconda.org/anaconda django

Install Google Api Client

cmd


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

Install oauth2client

https://github.com/google/oauth2client

cmd


pip install --upgrade oauth2client

Update just in case

http://mikegrouchy.com/blog/2014/06/pro-tip-pip-upgrade-all-python-packages.html

cmd


pip freeze --local | grep -v '^\-e' | cut -d = -f 1  | xargs pip install -U

Python execution

Creating a Python project

Create a directory to save the Python file and move the file you downloaded earlier to it.

Create a Python file.

This time, we will get a list of uploaded files. Some modifications have been made based on the "Get My Uploaded Video" script at the URL below.

https://developers.google.com/youtube/v3/code_samples/python?hl=ja#retrieve_my_uploads

Create a Python file that describes the script below. (This time named main.py) 010.png

main.py


#! env python
# -*- coding: utf-8 -*-

import httplib2
import os
import sys
import glob

from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow

if __name__ == '__main__':
    #Change the current directory to the location of the executable file
    os.chdir(os.path.dirname(os.path.abspath(sys.argv[0])))

    CLIENT_SECRETS_FILE = "client_id.json"  #Downloaded file name

    MISSING_CLIENT_SECRETS_MESSAGE = """
    WARNING: Please configure OAuth 2.0

    To make this sample run you will need to populate the client_secrets.json file
    found at:

       %s

    with information from the Developers Console
    https://console.developers.google.com/

    For more information about the client_secrets.json file format, please visit:
    https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
    """ % os.path.abspath(os.path.join(os.path.dirname(__file__),
                                       CLIENT_SECRETS_FILE))

    YOUTUBE_READONLY_SCOPE = "https://www.googleapis.com/auth/youtube.readonly"
    YOUTUBE_API_SERVICE_NAME = "youtube"
    YOUTUBE_API_VERSION = "v3"

    CLIENT_SECRETS_FILE_PATH = glob.glob(os.path.join(os.getcwd(), CLIENT_SECRETS_FILE))[0]

    flow = flow_from_clientsecrets(os.path.join(os.getcwd(), CLIENT_SECRETS_FILE_PATH),
                                   message=MISSING_CLIENT_SECRETS_MESSAGE,
                                   scope=YOUTUBE_READONLY_SCOPE)

    storage = Storage("%s-oauth2.json" % sys.argv[0])
    credentials = storage.get()

    if credentials is None or credentials.invalid:
        flags = argparser.parse_args()
        credentials = run_flow(flow, storage, flags)

    youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
                    http=credentials.authorize(httplib2.Http()))

    channels_response = youtube.channels().list(
        mine=True,
        part="contentDetails"
    ).execute()

    for channel in channels_response["items"]:
        uploads_list_id = channel["contentDetails"]["relatedPlaylists"]["uploads"]
        print("Videos in list %s" % uploads_list_id)
        playlistitems_list_request = youtube.playlistItems().list(
            playlistId=uploads_list_id,
            part="snippet",
            maxResults=50
        )
        while playlistitems_list_request:
            playlistitems_list_response = playlistitems_list_request.execute()

            for playlist_item in playlistitems_list_response["items"]:
                title = playlist_item["snippet"]["title"]
                video_id = playlist_item["snippet"]["resourceId"]["videoId"]
                print("%s (%s)" % (title, video_id))

            playlistitems_list_request = youtube.playlistItems().list_next(
                playlistitems_list_request, playlistitems_list_response)

First run

When executing in a terminal (command prompt for windows) on a virtual environment

cmd


cd (Python project directory)
python main.py

The first time you run it, the browser will start "(The name of the credential) is requesting the following permission." Will be displayed, so give permission.

Execution completed

After executing the above, the list of videos uploaded so far will be displayed on the console.

Other controls

Various controls other than list display are possible. Of course, when deleting a video, make sure to thoroughly verify it before doing so at your own risk.

https://developers.google.com/youtube/1.0/developers_guide_python

Recommended Posts

YouTube video management with Python 3
Get Youtube data with python
[GUI with Python] PyQt5-Layout management-
Password management with python: keyring
Play video with sound with python !! (tkinter / imageio)
FizzBuzz with Python3
Scraping with Python
Scraping with Python
Save video frame by frame with Python OpenCV
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Excel table creation with Python [Progress management table]
Excel with Python
Microcomputer with Python
Cast with python
Collect video information of "Singing with XX people" [Python] [Youtube Data API]
[Python] I made a Youtube Downloader with Tkinter.
Post youtube soaring title to twitter with python3
Serial communication with Python
Zip, unzip with python
Django 1.11 started with Python3.6
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
Learning Python with ChemTHEATER 03
Sequential search with Python
"Object-oriented" learning with python
Handling yaml with python
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Learn Python with ChemTHEATER
Run prepDE.py with python3
1.1 Getting Started with Python
Collecting tweets with Python
Binarization with OpenCV / Python
3. 3. AI programming with Python
Kernel Method with Python
Scraping with Python + PhantomJS
Posting tweets with python
Drive WebDriver with python
Use mecab with Python3
[Python] Redirect with CGIHTTPServer
Play youtube in python
Voice analysis with python
Think yaml with python
Operate Kinesis with Python
Getting Started with Python
Use DynamoDB with Python
Zundko getter with python