Skip to content

Instantly share code, notes, and snippets.

@kholidfu
Created August 14, 2017 14:35
Show Gist options
  • Save kholidfu/c4e82eedc538068acad6044ce3fede1b to your computer and use it in GitHub Desktop.
Save kholidfu/c4e82eedc538068acad6044ce3fede1b to your computer and use it in GitHub Desktop.
Export Youtube Channel Videos to CSV using Python3 + Youtube Api
import requests # or urllib
import csv
# get Youtube Data API Key
API_KEY = "" # insert your API key
# youtube channel ID
channel_id = "" # insert Youtube channel ID
page_token = ""
videos = []
next = True
while next:
url = ("https://www.googleapis.com/youtube/v3/search?key="
"{}&channelId={}&part=snippet,id"
"&order=date&maxResults=50&pageToken={}"
).format(
API_KEY,
channel_id,
page_token
)
resp = requests.get(url)
data = resp.json()
for i in data['items']:
videos.append(i)
# iterate through result pagination
is_next = data.get('nextPageToken')
if is_next:
page_token = is_next
else:
next = False
# structuring the data
rows = []
for i in videos:
title = i['snippet'].get('title')
description = i['snippet'].get('description', "")
videoId = "https://www.youtube.com/watch?v={}".format(
i['id'].get('videoId', ""))
# add special formula [=image("url")], so we can view the thumbnail in google docs spreadsheet
thumb = "=image(\"{}\")".format(i['snippet']['thumbnails'].get('default').get('url', ""))
rows.append(";".join([title, description, videoId, thumb]))
# data is now ready to write to csv file
# writing to csv file
path = "videos.csv"
with open(path, "w") as csv_file:
writer = csv.writer(csv_file, delimiter=";")
for row in rows:
writer.writerow(row.split(";"))
@pascualeb
Copy link

Hi, im pretty interested in use this program in order to use its output into an R script which aims to do some basic data analysis about a given youtube channel.
Unfortunately, I'm much of a noobie about this issues so there are some details i'm struggling to get yet.

What's the meaning of page_token, and how am I supposed to get it?

So sorry, as this will be probably an obvious question for you, and thank you in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment