iT邦幫忙

2021 iThome 鐵人賽

DAY 29
2
AI & Data

Python - 數位行銷分析與 Youtube API 教學系列 第 29

Youtube Reports API 教學 - 告一個段落

「鮭魚均,因為一場鮭魚之亂被主管稱為鮭魚世代,廣義來說以年齡和臉蛋分類的話這應該算是一種 KNN 的機器學習,不正經的數據分析師,畢業後把人生暫停了半年,在 Google 和 AWS 辦過幾場演講,緩下腳步的同時找了份跨領域工作。偶而慢跑、愛跟小動物玩耍。曾立過很多志,最近是希望當一個有細節的人。」


Youtube Reports API 教學 - 告一個段落

這是系列文的最後一篇實戰教學文章了,YouTube Reports API 能夠使開發人員安排報告的排程,並且批量下載生成報告。對於 YouTube Reports API 而言, API 支持預先所以定義好的報告內容,並且每個報告都包含一組針對頻道使用者或內容管理員 YouTube 資訊。靈活的追蹤每 Youtube 影片的影片資訊,也有了更加彈性的資料運用方式。這篇是 Python - 數位行銷的 Youtube 分析教學系列文章的第 29 篇,也是我參加 2021 iThome 鐵人賽中系列文章的第 29 天。

系列文章:Python — 數位行銷分析與 Youtube API 教學
昨日回顧:Youtube Reports API 教學 - 頻道中出報表

關於 YouTube Reports API

LOGO

YouTube Reports API 的目的在於,讓開發人員與使用者可以快速生成報告,並且對於報告進行取用和分析,對於 YouTube Reports API 的使用來說我們大致上分為幾個步驟。

  • 呼叫 reportTypes.list() 方法以搜尋頻道或內容管理員可以檢索的報告列表。
  • 呼叫 jobs.create() 方法來確定應該為頻道或內容管理員生成報告。隨後使用 API 的 jobs.list() 和 jobs.delete() 來檢索或更改正在生成的報告列表。
  • 呼叫 jobs.reports.list() 方法為特定作業生成的報告列表。響應中的每個資源都包含一個 downloadUrl 屬性,該屬性指定可以從中下載報告的 URL。
  • 發送授權的 GET 請求下載 URL 檢索報告。

得到了 Reports API 的結果後

在上一個章節中我們提到了 Reports API 回傳的結果,會是不按照順序的匯出資料列表資料,我們從中可以看見像是 9月24, 10月03, 10月10 等等的日期

Reports API

  • 利用 Report dates 回傳的 URL 資料,貼上最底下的 URL download,將會開始進行下載,直到100% 時,回傳 Download Complete! 資訊,這裡選擇 8/12 日的資料做下載測試

Reports API2

真的有成功嗎,確認一下 !

  • 查詢一下儲存地點,確認資料下載是否成功,從資料中確實可以看見資料被成功匯出至 local_file
if __name__ == '__main__':
    aa = input("jobID:")
    tt=time.strftime("%m%d_%H%M%S_", time.localtime())    
    parser = argparse.ArgumentParser()
    parser.add_argument('--content_owner', default='y..你的ID...Q') 
    parser.add_argument('--job_id', default=aa)
    parser.add_argument('--report_url', default=None)
    parser.add_argument('--local_file', default='Output/'+str(tt)+'output.csv')
    args = parser.parse_args(args=[])
    youtube_reporting = get_authenticated_service()
    
    if not args.job_id and not args.report_url:
        if list_reporting_jobs(youtube_reporting,
                               onBehalfOfContentOwner=args.content_owner):
            args.job_id = get_job_id_from_user()
            
    if args.job_id and not args.report_url:
        retrieve_reports(youtube_reporting,
                         jobId=args.job_id,
                         onBehalfOfContentOwner=args.content_owner)
        args.report_url = get_report_url_from_user()
    # Download the selected report.
    if args.report_url:
        download_report(youtube_reporting,args.report_url, args.local_file)

Analytics

  • 因為資料內容比較敏感,所以只能貼角落給大家看,但是可以得到所有影片相關的資料,包含觀看次數,各影片的相關觀看結果,得到結果為光是 8 月12 日的資料就能夠獲得33萬筆的資料,在大數據資料抓取上比起 Youtube Analytics API 還要方便得多。

AnalyticsAPI

  • 再次附上完整程式碼做總結
import argparse,os
import sys,time,csv
import google.oauth2.credentials
import google_auth_oauthlib.flow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from googleapiclient.http import MediaIoBaseDownload
from google_auth_oauthlib.flow import InstalledAppFlow
from io import FileIO
from datetime import datetime

CLIENT_SECRETS_FILE = 'client_secret_5....你的金鑰rcontent.com.json'
SCOPES = ['https://www.googleapis.com/auth/yt-analytics-monetary.readonly']
API_SERVICE_NAME = 'youtubereporting'

# Authorize the requests.
def get_authenticated_service():
    flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)
    credentials = flow.run_console()
    return build('youtubereporting','v1', credentials=credentials)

# Remove arguments word.
def remove_empty_kwargs(**kwargs):
    good_kwargs = {}
    if kwargs is not None:
        for key, value in kwargs.items():
            if value:
                good_kwargs[key] = value
    return good_kwargs

# Call the YouTube Reporting API's jobs.
def list_reporting_jobs(youtube_reporting, **kwargs):
    kwargs = remove_empty_kwargs(**kwargs)
    results = youtube_reporting.jobs().list(**kwargs).execute()
    if 'jobs' in results and results['jobs']:
        jobs = results['jobs']
        for job in jobs:
            print('YouTube Reporting API job id: %s\n name: %s\n for reporting type: %s\n'
                  % (job['id'], job['name'], job['reportTypeId']))
    else:
        print ('None jobs')
        return False
    return True

# Call the YouTube Reporting API's reports.list method to retrieve reports created by a job.
def retrieve_reports(youtube_reporting, **kwargs):
    kwargs = remove_empty_kwargs(**kwargs)
    results = youtube_reporting.jobs().reports().list(
        **kwargs
    ).execute()
    if 'reports' in results and results['reports']:
        reports = results['reports']
        for report in reports:
            print('Report dates: %s \n       download URL: %s\n'
                  % (report['startTime'], report['downloadUrl']))
#             print('Report dates: %s to %s\n       download URL: %s\n'
#                   % (report['startTime'], report['endTime'], report['downloadUrl']))

            
# Call the YouTube Reporting API's media.download method to download the report.
def download_report(youtube_reporting, report_url, local_file):
    request = youtube_reporting.media().download(
        resourceName=' '
    )
    request.uri = report_url
    fh = FileIO(local_file, mode='wb')
    downloader = MediaIoBaseDownload(fh, request, chunksize=-1)
    done = False
    while done is False:
        status, done = downloader.next_chunk()
        if status:
            print('Download %d%%.' % int(status.progress() * 100))
    print('Download Complete!')

# Prompt the user to select a job and return the specified ID.
def get_job_id_from_user():
    job_id = input('Please enter the job id for the report retrieval: ')
    print('You chose "%s" as the job Id for the report retrieval.' % job_id)
    return job_id

# Prompt the user to select a report URL and return the specified URL.
def get_report_url_from_user():
    report_url = input('Please enter the report URL to download: ')
    print('You chose "%s" to download.' % report_url)
    return report_url

Youtube Reports API 告一個段落啦!!!!!!!!!!!!!!!!

終於結束啦!!!!! 如果有時間也歡迎看看我的夥伴們的文章

lu23770127 — SASS 基礎初學三十天
10u1 — 糟了!是世界奇觀!
juck30808 — Python — 數位行銷分析與 Youtube API 教學
HLD — 淺談物件導向與Design Pattern介紹
SiQing47 — 前端?後端?你早晚都要全端的,何不從現在開始?

Jerry Chien

【鮭魚均】 現職是 200 多萬訂閱 Youtuber 的數據分析師,專長在 Python 的開發與使用,大學雖然是資訊背景但總是斜槓跑到商管行銷領域,以工作角度來說的話,待過 FMCG、通訊軟體、社群影音產業,也算是個數位行銷體系出生的資訊人。這 30 天鐵人挑戰賽會從數位行銷角度去重新切入數據分析這件事情,期待這個社會中,每個人能在各個角力間不斷沖突而漸能找到一個平衡點回歸最初的統計建立最終的初心。


上一篇
Youtube Reports API 教學 - 頻道中出報表
下一篇
Youtube API - 凡事趁早沒有那麼多來日方長(總結)
系列文
Python - 數位行銷分析與 Youtube API 教學30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
0
juck30808
iT邦研究生 1 級 ‧ 2021-10-14 10:09:26

同步發表至 MEDIUM,完賽啦!!完賽啦!!!完賽啦!!!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發表完賽啦!!完賽啦!!!完賽啦!!!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發表MEDIUM,完!!!完賽啦!!!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發完賽啦!!完賽啦!!!完賽!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發MEDIUM,完賽啦!!完完賽啦!!!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發表MEDIUM,完賽啦!!完賽啦!!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發DIUM,完賽啦!!完賽啦賽啦!!!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發表至 MEDIUM,完啦!!!完
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發表至 MEDIUM
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137
同步發表至 MEDIUM,完賽啦!!
https://medium.com/@juck30808/d29-youtube-reports-api-%E6%95%99%E5%AD%B8-%E5%91%8A%E4%B8%80%E5%80%8B%E6%AE%B5%E8%90%BD-16dfc94c4137

0
juck30808
iT邦研究生 1 級 ‧ 2021-10-14 11:25:21

--- 10/14完賽前重新更新錯字與圖片 ---

0
Shiva虛碼
iT邦新手 3 級 ‧ 2021-10-14 18:16:08

恭喜即將邁入完賽階段~/images/emoticon/emoticon12.gif

1
Rson Wilson
iT邦新手 4 級 ‧ 2021-10-15 00:30:52

鮭魚均加油!就要完賽啦~~~ (對著肝喊話

我要留言

立即登入留言