Python YouTube API Tutorial: Sort a Playlist by Most Popular Videos
22:08

Python YouTube API Tutorial: Sort a Playlist by Most Popular Videos

Corey Schafer 31.07.2020 49 697 просмотров 1 160 лайков

Machine-readable: Markdown · JSON API · Site index

Поделиться Telegram VK Бот
Транскрипт Скачать .md
Анализ с AI
Описание видео
In this Python Programming Tutorial, we'll be learning how to get the most popular videos in a YouTube playlist. I use scripts like this a lot personally when I don't have time to watch an entire playlist and want to only see the most-watched videos. Surprisingly YouTube doesn't have this ability on their site, but Python allows us to do this programmatically. Let's get started... The code for this video can be found at: https://bit.ly/YouTubeAPI-03 YouTube API Tutorial - https://youtu.be/th5_9woFJmk F-Strings Tutorial - https://youtu.be/nghuHvKLhJA Sorting Tutorial - https://youtu.be/D3JvDWO-BY4 Slicing Tutorial - https://youtu.be/ajrtAuDg3yw YouTube API Docs - https://developers.google.com/youtube/v3 Google API Python Client - https://github.com/googleapis/google-api-python-client ✅ Support My Channel Through Patreon: https://www.patreon.com/coreyms ✅ Become a Channel Member: https://www.youtube.com/channel/UCCezIgC97PvUuR4_gbFUs5g/join ✅ One-Time Contribution Through PayPal: https://goo.gl/649HFY ✅ Cryptocurrency Donations: Bitcoin Wallet - 3MPH8oY2EAgbLVy7RBMinwcBntggi7qeG3 Ethereum Wallet - 0x151649418616068fB46C3598083817101d3bCD33 Litecoin Wallet - MPvEBY5fxGkmPQgocfJbxP6EmTo5UUXMot ✅ Corey's Public Amazon Wishlist http://a.co/inIyro1 ✅ Equipment I Use and Books I Recommend: https://www.amazon.com/shop/coreyschafer ▶️ You Can Find Me On: My Website - http://coreyms.com/ My Second Channel - https://www.youtube.com/c/coreymschafer Facebook - https://www.facebook.com/CoreyMSchafer Twitter - https://twitter.com/CoreyMSchafer Instagram - https://www.instagram.com/coreymschafer/ #Python

Оглавление (12 сегментов)

Intro

hey there how's it going everybody in this video we're going to be using python and the youtube api to find the most popular videos in a playlist now i want to say right off the bat that this is going to be very similar to the last video i covered where we used python and the youtube api to calculate the total duration of a playlist so if you haven't watched that video yet then i'd recommend watching that first because i'm going to use our final script from that video as a starting point for this video so like i said we're going to be using python and the youtube api to find the most popular videos in a playlist now this is another script that i use a lot personally and let me show you why so i have the euro python 2019 playlist pulled up here in my browser now i like to watch conference videos to keep up to date with the latest changes in python and new techniques and technologies but i don't really have time to watch every talk from every conference we can see here uh that if i look at this playlist that there are if i scroll all the way to the bottom here there are about 133 talks uh that were uploaded to this conference playlist and a lot of these talks are 45 minutes to an hour so maybe i just want to watch the most popular videos from a specific playlist instead of watching every single video and on the youtube site there's not actually a way for us to sort these playlists by the most popular videos now if i go to their videos page here then i can sort by their most popular videos so if i go to their videos then we can click on most popular here but this is for their entire channel so we can see here that uh their most popular video was from eight years ago so that's definitely uh not from last year's conference so if i wanted to know the most popular video from a particular playlist then i'd have to go through and look at those views manually and doing this for different playlists just isn't really practical so we're going to learn how to find the most popular videos from a playlist automatically using python and the youtube api so with that said let's go ahead and get

Overview of Previous Script

started now like i said i'm going to use our final script from the playlist duration video as a starting point for what we want to do here and i've already got this pulled up here in my browser or i'm sorry i have this pulled up here in my editor and as usual i'll have a link to all the code in the description section below if anyone would like to follow along okay so the script that we have here that we wrote in the previous video will calculate the total duration of a playlist given a playlist id so let's go over this script here real quick and see what it does and then we'll look at how to adapt this script to do what we need okay so we are first importing some libraries here uh we are importing the google api client uh we're setting up our api key here and connecting to the youtube service uh here is where we have some regular expressions that will calculate the total time in a video and then what we are doing here is looping over all of the videos in a particular playlist and then we are making that uh execution to the api and then what we do here is we scroll through and grab all of the video ids here um and then we make a request to the videos resource using those video ids and then we loop through all of those responses for all of the videos in that playlist and in this example we're grabbing the total duration and parsing those out and then just adding those up so that we can get the total duration for a playlist now like i said i go much more in detail into this script in the previous video where we initially wrote this so that is a quick overview of our script okay so now that we've gone

Playlist ID

over this script to calculate the total duration now let's run this script here using that euro python playlist and then we'll think about how we want to change uh this script so that we're instead grabbing the most popular videos there are a few different ways that we can get the playlist id but i'm just going to go directly to the playlist that i want and grab that id directly so i want the euro python 2019 playlist let me pause this again here now if we go up to the url here one way to grab a playlist id is it's just a parameter here in the url so we can see i know that this is probably a little small on my monitor but we have one argument that says list is equal to and then a big long id and that is the playlist id so i'm just going to copy that and then now that we have that let's go paste this into our script from the last video now in the last video i put the playlist id directly here in our query just to make clear uh what the playlist id is let's go ahead and create a new variable here called playlist id i probably should have done this in the last video but that's okay we'll go ahead and do it here so i'm going to place that playlist id out here and now within our api query here i'm just going to use that variable instead of that string directly okay so

Modify Script

right now this script is going to calculate the total duration of an entire playlist so let's run this real quick to make sure that this is still working properly with this specific playlist so if we run this then we can see that this does seem to be working and it's telling us that the playlist has almost 77 hours worth of content so this is still working but now we want to modify this script to instead give us the most popular videos from this playlist so let's go ahead and start changing some of our code so first of all we're no longer going to need to do any calculations with the video durations so we can just go ahead and remove all of the stuff like you know date time and regular expression stuff that we were using before so let me scroll up here and see what we don't really need anymore uh so we're not going to need regular expressions since we were using that to parse out the duration of the videos we're not going to need the date time library anymore we're also not going to need our regular expressions here so i will just delete all of these compiled regular expressions we're not going to need total seconds and let me see what else down here so if i scroll down uh to where we were actually parsing out the duration from these videos we can get rid of these hours minutes and seconds here and also we can get rid of this section where we were converting these uh to a time delta or to total seconds and also i'm not going to need the total seconds here so and there's one more uh right here so i can take out i'll just take out this entire bottom part we are where we're calculating those total seconds uh and uh turning those into minutes or hours minutes and seconds and i'll get rid of the print statement as well okay so now i think we have i think the 38 lines that we have here basically just loops through a playlist and all of the videos in that specific playlist so just to say that again now that we've removed all of that code basically all that's left is that we are looping over all of the videos in a playlist and then making a request with each video id to get more detailed information about each video now right now the information that we're getting back is the video duration if i look um right

Documentation

here but we can instead change this so that we're getting the number of views that each video has instead that way we can sort these by the most popular videos so to figure out how to do this we can look at the documentation online and see what properties of the video we need to access and i have that open here in my browser so let's take a look at this documentation to see how we would figure this out okay so if you want to see what is available to you so right now we're in the videos resource here if we want to see what's available to us we can go down to resource representation so we can see here that it says the following json structure shows the format of a videos resource so if i look at this we can see that there's a lot of information here but the one that i would be interested in is if we go down here to statistics we can see that in statistics we have this view count now i'm going to base the most popular video based off of view count but if you wanted to you could also base it off of like count and or how many comments there are things like that so now we know that in order to get the view count for each video we need to access the statistics of each video and then we can access the view count from those statistics so let's go back to our script and add this so back in our script here up here where we had content details we no longer want the content details we want those uh statistics so i will put that in instead and now down here in our loop uh where we were looping through and getting the duration from those content details now we want to access the statistics and then within the statistics we want the view count now that is camelcase there again if you need to get a reference for that then you can look at the documentation we can see that it is camelcased here so now if i go back to the script

Creating YouTube Links

now i'm also going to change this variable name here instead of duration let's just call this vid underscore views okay now we're also going to want links to the most popular videos after we sort by uh view count so to create a youtube link all we need to do is grab the video id and then we can create a link manually ourselves so we can do this uh just by saying vid id is equal to now to access the id we can just say item and access the id key and now to create a link manually what we can do here is i'll just create an f string and this is going to be https colon forward slash now here's how youtube links are structured so this is the shorthand uh youtube links here so u2 dot be and then we can just do a forward slash and then pass in the video id so i will go ahead and do that

Creating a Global List

okay so right now let's think about what we've done here so far so we are looping over the playlist and we are accessing each video in that playlist and then we are grabbing the view counts and creating a link for each video in the playlist so now in order to sort these we can simply add all of this information to a list and then sort the list based on the number of views so first let's create a global list here where we can add this information so up here at the top which is outside of our loop right above this next page token here i'm just going to create an empty list with a variable name of videos and the information that we're going to add for each video is going to be the view count and the link for that video so each video can just be a dictionary with those two pieces of information so down here back under our video id and youtube link let's just append this information to our videos list so i'll say videos dot append and now what we want to append is going to be dictionary information so let me get this looking correct okay so first i'm going to add the information for the views and the views will just be we could do video views here now i'm not sure how this information comes back i think as a string so just to make sure that this is an integer that we can sort on let's go ahead and cast this to an integer just to be sure because if it was a string then it wouldn't uh work correctly all of the ones so a one and a one hundred would come before two but if it's an integer then you know it'd be one two and then a hundred so hopefully that makes sense and now let's also add the url here and the url is just going to be that youtube link okay so now we are adding uh each of these videos information to our videos list as a dictionary so our videos list is going to be a list of dictionaries so

Print Video URLs

before we sort this let's just print out some of these values and see if our script is working so far because we've actually written a good bit of code so far without testing that any of this is working so far so back on our main level here outside of that while loop let's loop over our videos and print out the url and view count for each video so to do this we can just say 4 video in videos and i will print out remember this is a dictionary so i'm just going to print out the video and access that url key and i'll also print out the video views and access that views key

Print Video Length

and also while we're at it let's go ahead and also print out the number of videos in our videos list if you remember back at the beginning of the video we saw that there were 133 videos in the playlist for this conference so we should probably check to make sure that those numbers are matching up correctly so outside of our for loop here i'm going to print the length of our videos list okay so now let's run this and see if what we have so far is working okay so we can see down here at the bottom that it did print out that there are 133 videos and each of these videos prints out the url and view count of each video so now we should be able to simply uh sort our list of videos in order to get the most popular videos first now if you're unfamiliar with sorting and python then i do have a video specifically on sorting and i'll be sure to leave a link to that video in the description section below in case anyone is interested but in this case since we're sorting a list of dictionaries then we'll have to pass in our own custom key so let me actually sort this videos list in place before i loop over these videos so to sort a list in place we can just say videos. sort and now we need to pass in our own custom key now this custom key is going to be a function uh telling python what we want to sort these videos on now this could be a function that we write ourselves up here but if you just want to write an inline function then we can write a lambda function which is basically just an anonymous function but if you aren't familiar with lambda functions then you can always just write your own custom function as well but to do a lambda function we can just say lambda and then what our variable is going to be i'll just call this vid and now we need to specify our return value here so what this is saying is okay when you're looping through this list here you're going to see a bunch of videos so what do we want to sort on with these videos vid and access that views key and sort on that views key now uh by default this will sort in ascending order so the lowest views will be first and then go down to the highest views we actually want to get the highest views first

Highest Views

so we can just say that we want reverse is equal to true and that will give us the um the highest viewed videos first and also let me go ahead and remove our print statement for the length of videos as well since we already made sure that looked right okay so now if we run this code then scroll up here at the top then our output should be sorted with all of the most popular videos of this playlist at the top so we can see here that the most watched talk from this conference had over uh 5 500 views and if we copy the link and paste this into our browser just to make sure that this is a valid link then we can see that yes we have the same number of views here 5 almost 5 500 and it looks like this was a video on python versus rust for simulation so you know that might be a cool video to watch if that's something that sounds interesting to you

List Slicing

so we've pretty much done what we set out to do here now if you'd like to see you know just the top 10 videos or something like that then instead of print looping over the entire playlist we could always just use list slicing when printing out this information so for example to see the top 10 videos from this conference then right here where we are looping over these videos i could just use list slicing here and say that we want up to the 10th video so if i run this then this will you can see that we have a lot less videos here now and that will simply loop over the first 10 values of our sorted list now you might notice some discrepancies here with the views it says that this is 5500 here and if we go back to our browser it says that this is only 5400 or so the reason is uh because sometimes the information that is displayed publicly might not get updated all the time um but it's just a small difference here sometimes the api data can be slightly different than what's on the front page just depending on how often uh each section gets updated but like i said this is pretty much what we set out to do here uh so now we have a way to grab the you know the top viewed videos from a specific playlist now if you'd like to take this a step further with practicing programming then there are a lot of ways that we could do something like this but maybe with a better front end so for example you could create a web application either using flask or django that allows people to paste in a playlist and then sort playlists like this and then display the embedded videos on a web page in that order so that they can go through them each individually doing things like that is always good for learning to take what we learn in these videos and apply them to larger projects in some way

Outro

and like i said just writing scripts like this for myself i use scripts like this all the time whenever you know i'm watching a particular playlist and i just want to watch the most popular ones okay so i think that's going to do it for this video i hope you feel like you have a better grasp of using the youtube api with python and also getting an idea of some of the cool and practical things that we can do with this knowledge now like i said i've already seen some comments from a few different viewers that said that they were going to turn the tools that we're building here into either flask or django web applications so that the general public can use tools like this as well and i think that's a great idea it's you know it's also possible to take the knowledge that we learn here in these areas and make some good supplemental income so for example if you use the api to create something useful like we did here for others and then put it into a website for the general public to use then i could definitely see that bringing in some extra income based on the traffic coming to your site so yeah i always think it's a good idea to take what we learn here and maybe try to adapt it to your own and put it into maybe an app or a website or something like that but if anyone has any questions about what we covered in this video then feel free to ask in the comments section below and i'll do my best to answer those and if you enjoy these tutorials and would like to support them then there are several ways you can do that the easiest way is to simply like the video and give it a thumbs up and also it's a huge help to share these videos with anyone who you think would find them useful and if you have the means you can contribute through patreon or youtube and there are links to those pages in the description section below be sure to subscribe for future videos and thank you all for watching

Другие видео автора — Corey Schafer

Ctrl+V

Экстракт Знаний в Telegram

Экстракты и дистилляты из лучших YouTube-каналов — сразу после публикации.

Подписаться

Дайджест Экстрактов

Лучшие методички за неделю — каждый понедельник