Pythonを使用してYouTubeのデータをスクレイピングする方法について説明します。この記事では、特にSeleniumとBeautifulSoupを使用した方法と、YouTube Data APIを使用した方法について説明します。
SeleniumとBeautifulSoupを使用した方法
SeleniumとBeautifulSoupを使用してYouTubeのデータをスクレイピングする方法は、ウェブページの動的な内容を取得するのに適しています。例えば、特定のYouTubeチャンネルの全動画のタイトルとURLを取得することができます。
以下に、SeleniumとBeautifulSoupを使用してYouTubeの急上昇(音楽)の動画タイトルとURLをCSVファイルに書き出すサンプルコードを示します。
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import pandas as pd
from time import sleep
chrome_path = r'C:\\Users\\デスクトップ\\python\\selenium_test\\chromedriver'
def get_youtube_trending_music_info(url, outputFileName):
options = Options()
options.add_argument('--incognito')
driver = webdriver.Chrome(executable_path=chrome_path, options=options)
driver.get(url)
driver.implicitly_wait(10)
xpath = '//*[@id=\"tabsContent\"]/tp-yt-paper-tab[2]'
driver.find_element_by_xpath(xpath).click()
sleep(2)
music_ranking_videos = driver.find_elements_by_id('video-title')
titles = []
urls = []
for music_ranking_video in music_ranking_videos:
titles.append(music_ranking_video.text)
urls.append(music_ranking_video.get_attribute('href'))
if len(titles) == 10:
break
df = pd.DataFrame()
df['trending_rank'] = range(1, 11)
df['title'] = titles
df['URL'] = urls
df.to_csv(outputFileName)
driver.quit()
if __name__ == '__main__':
url = 'https://www.youtube.com/feed/trending'
outputFileName = 'youtube_trending_music_rank.csv'
get_youtube_trending_music_info(url, outputFileName)
YouTube Data APIを使用した方法
YouTube Data APIを使用すると、YouTubeのデータを直接取得することができます。これにより、検索結果、サムネイル画像、チャンネル登録者などの情報を取得することができます。
以下に、YouTube Data APIを使用して「筋トレ」で検索した際の検索結果を取得するサンプルコードを示します。
from apiclient.discovery import build
from apiclient.errors import HttpError
DEVELOPER_KEY = 'APIキーを入力'
YOUTUBE_API_SERVICE_NAME = 'youtube'
YOUTUBE_API_VERSION = 'v3'
youtube = build(
YOUTUBE_API_SERVICE_NAME,
YOUTUBE_API_VERSION,
developerKey=DEVELOPER_KEY
)
search_response = youtube.search().list(
q='筋トレ',
part='id,snippet'
).execute()
print(search_response)
以上、Pythonを使用したYouTubeスクレイピングの基本的な方法について説明しました。これらの方法を活用して、YouTubeのデータを効率的に取得し、分析や研究に役立ててください。.