人気動画の傾向を、毎日簡単チェック!
TikTokやYouTubeの人気動画を収集し、流行の傾向を分析するプログラム を作成できます。
🎯 実装のポイント
✅ YouTube → YouTube Data API v3 を使用
✅ TikTok → 非公式APIまたはSeleniumでスクレイピング
⚠ 注意: TikTokの公式APIは一部制限があり、Seleniumなどのブラウザ自動操作が必要な場合があります。
🚀 Pythonコード: YouTube & TikTokトレンド収集
🔹 手順
- YouTubeのトレンド動画を取得(API使用)
- TikTokのトレンド動画を取得(Seleniumを使用)
- データをExcelに保存
- 人気のキーワード分析(ワードクラウド生成)
📝 必要なライブラリのインストール
pip install google-auth google-auth-oauthlib google-auth-httplib2
googleapiclient pandas openpyxl selenium wordcloud matplotlib
👉 Seleniumでブラウザを操作するため、ChromeDriverが必要
👉 Chromeのバージョンに合った ChromeDriver をダウンロードし、パスを通す
🎬 YouTube & TikTokのトレンドデータ取得
import requests
import json
import pandas as pd
import time
from googleapiclient.discovery import build
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# ======= YouTube API設定 =======
YOUTUBE_API_KEY = "あなたのYouTube APIキー"
youtube = build("youtube", "v3", developerKey=YOUTUBE_API_KEY)
# ======= TikTokスクレイピング設定 =======
CHROMEDRIVER_PATH = "/path/to/chromedriver" # ChromeDriverのパスを指定
chrome_options = Options()
chrome_options.add_argument("--headless") # ヘッドレスモード(画面なしで実行)
# Excelファイルの初期化
excel_filename = "trending_videos.xlsx"
writer = pd.ExcelWriter(excel_filename, engine="openpyxl")
# 1️⃣ **YouTubeのトレンド動画取得**
def get_youtube_trending():
response = youtube.videos().list(
part="snippet,statistics",
chart="mostPopular",
regionCode="JP", # 日本のトレンド
maxResults=10
).execute()
video_data = []
for video in response["items"]:
title = video["snippet"]["title"]
channel = video["snippet"]["channelTitle"]
views = video["statistics"].get("viewCount", 0)
likes = video["statistics"].get("likeCount", 0)
video_id = video["id"]
url = f"https://www.youtube.com/watch?v={video_id}"
video_data.append([title, channel, views, likes, url])
df = pd.DataFrame(video_data, columns=["タイトル", "チャンネル", "視聴回数", "いいね数", "URL"])
df.to_excel(writer, sheet_name="YouTube", index=False)
print("✅ YouTubeトレンドデータ取得完了")
return df
# 2️⃣ **TikTokのトレンド動画取得(スクレイピング)**
def get_tiktok_trending():
service = Service(CHROMEDRIVER_PATH)
driver = webdriver.Chrome(service=service, options=chrome_options)
driver.get("https://www.tiktok.com/foryou") # トレンドページ
time.sleep(5) # 読み込み待ち
videos = driver.find_elements(By.CSS_SELECTOR, 'div[data-e2e="video-item"]')
tiktok_data = []
for video in videos[:10]: # 上位10件取得
try:
title = video.find_element(By.CSS_SELECTOR, "h3").text
user = video.find_element(By.CSS_SELECTOR, "h4").text
url = video.find_element(By.TAG_NAME, "a").get_attribute("href")
tiktok_data.append([title, user, url])
except:
continue
driver.quit()
df = pd.DataFrame(tiktok_data, columns=["タイトル", "ユーザー", "URL"])
df.to_excel(writer, sheet_name="TikTok", index=False)
print("✅ TikTokトレンドデータ取得完了")
return df
# 3️⃣ **トレンド動画のキーワード分析**
def generate_wordcloud(df, platform):
text = " ".join(df["タイトル"])
wordcloud = WordCloud(width=800, height=400, background_color="white", font_path="/path/to/your/font.ttf").generate(text)
plt.figure(figsize=(10, 5))
plt.imshow(wordcloud, interpolation="bilinear")
plt.axis("off")
plt.title(f"{platform} トレンドワードクラウド")
plt.savefig(f"{platform}_wordcloud.png")
plt.show()
# ======= 実行 =======
df_youtube = get_youtube_trending()
df_tiktok = get_tiktok_trending()
# Excelファイル保存
writer.close()
print("✅ データをExcelに保存しました")
# ワードクラウド生成
generate_wordcloud(df_youtube, "YouTube")
generate_wordcloud(df_tiktok, "TikTok")
✅ プログラムの動作
- YouTube API で 日本のトレンド動画(最大10件) を取得
- TikTokのトレンド動画(最大10件) を Seleniumでスクレイピング
- Excelファイルにデータ保存(タイトル・ユーザー・URL)
- ワードクラウドでトレンドキーワードの可視化
🎯 今後の改善ポイント
- データ量を増やす(最大50〜100件)
- TikTok公式APIを利用(現在制限あり)
- 日本語形態素解析(janome / MeCab)でトレンドワードの精度向上
- データベース(SQLite / MySQL)に保存し、過去トレンドと比較分析
🔥 まとめ
✅ Pythonで YouTube API & Selenium を活用
✅ トレンド動画をExcelに自動保存
✅ ワードクラウドで流行の傾向を分析
このプログラムを動かせば、YouTube & TikTok のトレンドを毎日収集して分析 できます!✨
さらに発展させたい場合は教えてください! 🚀
0 件のコメント:
コメントを投稿
こみつです。よろしく!