Anni's Blogs

Export a YouTube Playlist to a csv

As I student I find YouTube to be an invaluable resource to learn new things- be it how to pass my Database Management Systems End-Semester exam the next day (thank you Gate Smashers) or the fundamentals of ML (thank you Andrew Ng).

Tracking my progress and keeping track of the videos I’ve already watched, therefore, seems like a natural thing to do. However, I was sad to learn that there’s no in-built way to “export” the titles etc. of a YouTube playlist to a Google Sheet (@Google if you’re reading this- please add this feature maybe?)

So post some Googling (yes, not GPTing), here’s a few code-snippets to achieve the above! It requires typing in commands into the "Console" tab of the Developer Tools. On Chrome and Brave, you can access the Developer Tools by right-clicking on the page and clicking the "Inspect" option following which a panel should pop up on the right side of the screen.

Step 1:

Sometimes YT playlists don’t load fully i.e. if there are 500 videos in a playlist, only the first 20 loads into the DOM and more videos are fetched as you scroll down. So to load all videos into the html page, we must scroll down using:

let goToBottom = setInterval(() => window.scrollBy(0, 400), 1000);

Step 2:

Now that we’ve scrolled to the bottom, all the video titles, durations etc are loaded onto the current HTML page. All that’s remaining is to find the correct divs and their ids to extract the title, duration etc.

clearInterval(goToBottom);
let arrayVideos = [];
console.log('\n'.repeat(50));
const videoItems = document.querySelectorAll('ytd-playlist-video-renderer.style-scope');

for (const item of videoItems) {
    const titleElement = item.querySelector('a#video-title');
    const durationElement = item.querySelector('ytd-thumbnail-overlay-time-status-renderer span#text');
    
    if (titleElement && durationElement) {
        const title = titleElement.title;
        const url = titleElement.href.split('&list=')[0];
        const duration = durationElement.textContent.trim();
        
        arrayVideos.push(`${title};${url};${duration}`);
        console.log(`${title}\t${url}\t${duration}`);
    }
}

Step 3:

Now that we have the array in our Javascript console memory, let’s export it to CSV file!

let data = arrayVideos.join('\n');
let blob = new Blob([data], {type: 'text/csv'});
let elem = window.document.createElement('a');
elem.href = window.URL.createObjectURL(blob);
elem.download = 'my_data.csv';
document.body.appendChild(elem);
elem.click();
document.body.removeChild(elem);

And that's it! You now have a csv file of all the videos in the playlist. I like to convert it to .xlsx and then track my progress through the playlist by colouring the rows green as I watch the videos. It fills me up with an oddly satisfying and calming sensation.