5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

勘からデータへ:PythonとYouTube Data API v3によるYouTubeショート分析パイプラインの構築

Posted at

image.png

*こちらの記事は、英語から日本語へ翻訳をしています。

English Original Text

I’m Anshika Kankane, a data scientist at GIFTech, and I’m back to share another project—this time, it’s not about AI managers, but about how we’re trying to make things trend on YouTube.

We’ve recently been working on a project to grow the reach of our "giftech" YouTube channel by leaning into YouTube Shorts. Like any creator or marketer, we found ourselves staring at the blank upload screen wondering: "How do we actually make these videos trend?"

Instead of just guessing or chasing random memes, I decided to treat it like a data problem. I decided to use my background in data science to analyze what’s actually working on the platform. My plan was to use YouTube video analytics to get a clear idea of which narratives, keywords, and tags could help our videos gain traction. In this post, I’ll walk you through how I built a custom scraper using Python and the YouTube Data API v3, the bottlenecks I faced, and how I’m using this data to optimize our content strategy.

🧠 The Strategy: Data > Guesswork

The goal was simple: scrape the competition. I wanted to see what the top-performing videos in our niche were doing differently.

To do this, I built a custom scraper using Python and the YouTube Data API v3. I didn't just want view counts; I wanted the "hidden" metadata—transcripts, sponsorship markers, and specific tag combinations. In total, I collected 25 distinct data fields per video, including subscriber counts, view-to-like ratios, and even age-restricted flags.

The Engineering Part: Building the Scraper

My tech stack was straightforward:

  • Python 3.10
  • google-api-python-client: The bridge to the YouTube API.
  • youtube-transcript-api: To "hear" what was being said in the videos.
  • Pandas: My heavy lifter for data cleaning and analysis.

🚀 The Good: Automation & Resilience

The coolest part of this setup is the depth and the "fail-safe" loop I built.

1. Progressive Saving (My Life Saver)
When you're scaling a search across 30+ keywords and thousands of videos, the script can run for a while. I implemented progressive saving, which writes the data to the CSV after each keyword is processed. This means if I hit my daily API limit or my cat pulls the power cord, I don't lose the hours of work already completed.

2. Sponsorship Detector
I use Regular Expressions (Regex) to scan descriptions for keywords like "#ad" or "sponsored." This lets us differentiate between a video that trended because of a massive paid push versus one that trended organically.

⚠️ The Bad: The API Bottlenecks

Building this wasn't all smooth sailing. Here were my two main technical challenges:

1. The Quota Crunch & Caching
The YouTube API gives you a "free tier" of 10,000 units a day. That sounds like a lot until you realize that searching and fetching video details can eat that up in minutes.
💡 Pro Tip: I implemented a local cache for channel metadata. If a creator appears multiple times in my search results, my script only asks the API for their subscriber count once, saving about 1 unit per hit.

2. The 100-Result Pagination Barrier
YouTube’s search only gives you a few results per page. To fetch 100 results per keyword, I had to implement a pagination loop using nextPageToken.

def search_videos(self, query, max_results=100):
    video_ids = []
    next_page_token = None
    
    while len(video_ids) < max_results:
        search_response = self.youtube.search().list(
            q=query,
            part='id',
            maxResults=min(100, max_results - len(video_ids)),
            pageToken=next_page_token,
            type='video'
        ).execute()
        
        # Collect IDs and move to the next page
        video_ids.extend([item['id']['videoId'] for item in search_response.get('items', [])])
        next_page_token = search_response.get('nextPageToken')
        
        if not next_page_token:
            break
            
    return video_ids

🧹 Data Cleansing: The Data Scientist's Taxes

You can't just feed raw API data into a strategy. My cleaning script handled:

  • Deduplication: I added a filtering step to check if a keyword had already been scraped in a previous run to avoid redundant API calls.
  • Shorts Isolation: I filtered for videos under 70 seconds.
  • Tag Explosion: Since YouTube returns tags as one long string, I used .explode() in Pandas to turn one row into 15+ rows—one for each tag. This is how I can calculate which specific tag actually moves the needle.
  • The Japanese Regex: I isolated tags with Kanji/Kana to keep our insights focused on the Japanese market.

🔍 The Analysis: Looking for "Blue Oceans"

Once the data is cleaned, I look for the gap: tags that have a massive maximum view count (views_max) but a low video count (competition). If a tag has millions of views but only 5 videos using it, that's our "Blue Ocean" and where we want our giftech content to land.

Final Thoughts

After building and running this for a few days, my conclusion is: Absolutely, it was worth to get these useful insights.

By building your own pipeline, you're not just following trends—you're identifying them before they hit the "Trending" tab. Building this pipeline taught me that YouTube success is part art and part science. I’m no longer throwing darts in the dark for our giftech channel. Instead, I’m using data to find the right narrative, the most effective keywords, and the tags that actually convert into views.

If you're a data nerd or a developer looking to break into content, build your own tools. The insights you find in your own .csv files are worth more than any generic trend report.

Lastly

If you're interested in watching our shorts and showing support to us then please check our youtube channel and like it.
Youtube channel link

Thank you for your time.

GIFTechのデータサイエンティスト、Anshika Kankaneです。また新しいプロジェクトを皆さんに共有するために戻ってきました。今回はAIエージェントではなく、YouTubeで動画をバズらせるための挑戦についてです。

私たちは最近、**「giftech」**YouTubeチャンネルのリーチを広げるために、YouTubeショートに注力するプロジェクトに取り組んでいます。多くのクリエイターやマーケターと同じように、私たちもアップロード画面を前にして、「どうすればこの動画をトレンドに乗せられるんだろう?」と頭を抱えていました。

単に勘に頼ったり、適当なミームを追いかけたりする代わりに、私はこれを「データの課題」として捉えることにしました。データサイエンスのバックグラウンドを活かして、プラットフォーム上で実際に何がうまくいっているのかを分析することにしたのです。私の計画は、YouTube動画の分析データを活用して、どのようなナラティブ(語り口)、キーワード、タグが動画の成長に役立つのかを明確にすることでした。この記事では、PythonとYouTube Data API v3を使ってカスタムスクレイパーを構築した方法、直面したボトルネック、そしてこのデータをコンテンツ戦略の最適化にどう活用しているかを紹介します。

🧠 戦略:データ > 勘

目標はシンプルです。「競合を分析すること」。私たちのニッチ分野でトップパフォーマンスを出している動画が、他と何が違うのかを突き止めたかったのです。

そのために、PythonとYouTube Data API v3を使ってカスタムスクレイパーを構築しました。単に再生回数を知るだけでなく、文字起こし(トランスクリプト)、スポンサーの有無、具体的なタグの組み合わせといった「隠れた」メタデータが欲しかったのです。最終的に、登録者数、再生回数対いいねの比率、年齢制限のフラグなど、1動画あたり25種類のデータ項目を収集しました。

エンジニアリング編:スクレイパーの構築

技術スタックは非常にシンプルです:

  • Python 3.10
  • google-api-python-client: YouTube APIへのブリッジ
  • youtube-transcript-api: 動画で何が話されているかを「聴く」ため
  • Pandas: データクレンジングと分析の要

🚀 良かった点:自動化と回復力

このシステムの最もクールな点は、その深さと、私が構築した「フェイルセーフ(失敗に強い)」ループです。

1. プログレッシブ保存(私の命の恩人)
30以上のキーワードにわたって数千の動画を検索する場合、スクリプトの実行には時間がかかります。私は、キーワードごとに処理が終わるたびにCSVにデータを書き込む**「プログレッシブ保存」**を実装しました。これにより、1日のAPIリミットに達したり、飼い猫に電源コードを抜かれたりしても、それまでの数時間の作業が無駄になることはありません。

2. スポンサー検出機能
正規表現(Regex)を使って、概要欄から「#ad」や「sponsored(提供)」といったキーワードをスキャンするようにしました。これにより、純粋にオーガニックにトレンド入りした動画と、多額の広告費が投入された動画を区別できるようになりました。

⚠️ 苦労した点:APIのボトルネック

構築はすべてが順風満帆だったわけではありません。主な技術的課題は次の2点でした。

1. クォータの制限とキャッシング
YouTube APIの無料枠は1日10,000ユニットです。これは多く聞こえるかもしれませんが、大量の動画詳細を取得すると、数分で使い切ってしまいます。
💡 プロのアドバイス:チャンネルメタデータのローカルキャッシュを実装しました。同じクリエイターが検索結果に何度も登場する場合、スクリプトは登録者数をAPIに一度しか照会しないため、1ヒットあたり約1ユニットを節約できます。

2. 100件のページネーションの壁
YouTubeの検索結果は一度に数件しか取得できません。1キーワードあたり100件の結果を取得するために、nextPageTokenを使ったページネーションループを実装する必要がありました。

def search_videos(self, query, max_results=100):
    video_ids = []
    next_page_token = None
    
    while len(video_ids) < max_results:
        search_response = self.youtube.search().list(
            q=query,
            part='id',
            maxResults=min(100, max_results - len(video_ids)),
            pageToken=next_page_token,
            type='video'
        ).execute()
        
        # IDを収集し、次のページへ移動
        video_ids.extend([item['id']['videoId'] for item in search_response.get('items', [])])
        next_page_token = search_response.get('nextPageToken')
        
        if not next_page_token:
            break
            
    return video_ids

🧹 データクレンジング:データサイエンティストの宿命

生のAPIデータをそのまま戦略に使うことはできません。私のクレンジングスクリプトでは以下の処理を行いました:

  • 重複排除: 無駄なAPI呼び出しを避けるため、以前の実行ですでに取得済みのキーワードをチェックするステップを追加しました。
  • ショート動画の隔離: 70秒未満の動画のみにフィルタリングしました。
  • タグの展開(Explode): YouTubeのタグは一つの長い文字列として返されます。Pandasの.explode()を使って、1行を複数の行(1タグ1行)に変換しました。これにより、どの特定のタグが実際に効果を発揮しているかを計算できるようになります。
  • 日本語の正規表現: 日本市場に特化するため、漢字や仮名を含むタグのみを隔離しました。

🔍 分析: 「ブルーオーシャン」を探す

クレンジングが終わったら、「ギャップ」を探します。具体的には、**最大再生回数(views_max)**は非常に高いのに、**動画数(競合)**が少ないタグを見つけ出します。数百万回再生されているのに、それを使っている動画が5本しかないようなタグがあれば、それこそが私たちの「ブルーオーシャン」であり、giftechのコンテンツをぶつけるべき場所なのです。

終りの言葉

数日間このシステムを運用してみた結論は、**「間違いなく、有用な洞察を得る価値がありました」**です。

独自のパイプラインを構築することで、単にトレンドを追いかけるのではなく、トレンドが「トレンドタブ」に載る前に特定できるようになります。このパイプラインの構築を通じて、YouTubeでの成功は「アート」と「サイエンス」の両輪であることを学びました。私たちはもはや、「giftech」チャンネルのために暗闇でダーツを投げているわけではありません。代わりに、データを使って正しいナラティブ、最も効果的なキーワード、そして実際に視聴回数に繋がるタグを見つけ出しているのです。

データオタクや、コンテンツ制作に参入しようとしているデベロッパーの方は、ぜひ自分専用のツールを作ってみてください。自分自身の.csvファイルから得られる洞察は、巷にあふれるトレンドレポートよりもずっと価値があります。

最後に

もし私たちのショート動画に興味があり、応援していただけるのであれば、ぜひYouTubeチャンネルをチェックして「いいね」をお願いします。
YouTube チャンネルリンク

お時間をいただきありがとうございました。

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?