The Wayback Machine - https://web.archive.org/web/20240910212157/https://www.geeksforgeeks.org/how-to-extract-youtube-data-in-python/
Open In App

How to extract youtube data in Python?

Last Updated : 17 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisites: Beautifulsoup

YouTube statistics of a YouTube channel can be used for analysis and it can also be extracted using python code. A lot of data like viewCount, subscriberCount, and videoCount can be retrieved. This article discusses 2 ways in which this can be done.

Method 1: Using YouTube API

First we need to generate an API key. You need a Google Account to access the Google API Console, request an API key, and register your application. You can use Google APIs page to do so.

To extract data we need the channel id of the YouTube channel whose stats we want to view. To get the channel id visit that particular YouTube channel and copy the last part of the URL (In the examples given below channel id of GeeksForGeeks channel are used). 

Approach

  • First create youtube_statistics.py 
  • In this file extract data using YTstats class and generate a json file will all the data extracted.
  • Now create main.py
  • In main import youtube_statistics.py
  • Add API key and channel id
  • Now using the first file data corresponding to the key given will be retrieved and saved to json file.

Example :

Code for main.py file :

Python3




from youtube_statistics import YTstats
 
# paste the API key generated by you here
API_KEY = "AIzaSyA-0KfpLK04NpQN1XghxhSlzG-WkC3DHLs"
 
 # paste the channel id here
channel_id = "UC0RhatS1pyxInC00YKjjBqQ"
 
yt = YTstats(API_KEY, channel_id)
yt.get_channel_statistics()
yt.dump()


Code for youtube_statistics.py file :

Python3




import requests
import json
 
 
class YTstats:
 
    def __init__(self, api_key, channel_id):
        self.api_key = api_key
        self.channel_id = channel_id
        self.channel_statistics = None
 
    def get_channel_statistics(self):
        url = f'https://www.googleapis.com/youtube/v3/channels?part=statistics&id;={self.channel_id}&key;={self.api_key}'
 
        json_url = requests.get(url)
        data = json.loads(json_url.text)
 
        try:
            data = data["items"][0]["statistics"]
        except:
            data = None
 
        self.channel_statistics = data
        return data
 
    def dump(self):
        if self.channel_statistics is None:
            return
 
        channel_title = "GeeksForGeeks"
        channel_title = channel_title.replace(" ", "_").lower()
 
        # generate a json file with all the statistics data of the youtube channel
        file_name = channel_title + '.json'
        with open(file_name, 'w') as f:
            json.dump(self.channel_statistics, f, indent=4)
        print('file dumped')


Output:

Method 2: Using BeautifulSoup

Beautiful Soup is a Python library for pulling data out of HTML and XML files. In this approach we will use BeautifulSoup and Selenium to scrape data from YouTube channels. This program will tell the views, time since posted, title and urls of the videos and print them using Python’s formatting.

Approach

  • Import module
  • Provide url of the channel whose data is to be fetched
  • Extract data
  • Display data fetched.

Example:

Python3




# import required packages
from selenium import webdriver
from bs4 import BeautifulSoup
 
# provide the url of the channel whose data you want to fetch
urls = [
]
 
 
def main():
    driver = webdriver.Chrome()
    for url in urls:
        driver.get('{}/videos?view=0&sort;=p&flow;=grid'.format(url))
        content = driver.page_source.encode('utf-8').strip()
        soup = BeautifulSoup(content, 'lxml')
        titles = soup.findAll('a', id='video-title')
        views = soup.findAll(
            'span', class_='style-scope ytd-grid-video-renderer')
        video_urls = soup.findAll('a', id='video-title')
        print('Channel: {}'.format(url))
        i = 0  # views and time
        j = 0  # urls
        for title in titles[:10]:
            print('\n{}\t{}\t{}\thttps://www.youtube.com{}'.format(title.text,
                                                                   views[i].text, views[i+1].text, video_urls[j].get('href')))
            i += 2
            j += 1
 
 
main()


Output



Previous Article
Next Article

Similar Reads

How to Extract YouTube Comments Using Youtube API - Python
Prerequisite: YouTube API Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video et
2 min read
GUI to get views, likes, and title of a YouTube video using YouTube API in Python
Prerequisite: YouTube API, Tkinter Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, Tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with Tkinter is the fastest and easiest way to create GUI applications. In this art
2 min read
How to extract image information from YouTube Playlist using Python?
Prerequisite: YouTube API Google provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Data API is very simple to use provides features like – Search for videosHandle videos like retrieve information about a video, insert a video, delete a video, et
2 min read
Extract Video Titles with the Youtube API in Python
Extracting video titles from YouTube can be incredibly useful for various applications, such as data analysis, content creation, and trend tracking. The YouTube Data API provides a robust way to interact with YouTube's platform and extract this information. This guide will walk you through the process of extracting video titles using the YouTube AP
4 min read
Youtube Data API for handling videos | Set-1
Before proceeding further let's have a look at what we have in store for the videos section. Youtube Data API allows to perform following operations on the video: list insert update rate getRating reportAbuse delete Let's discuss how to use Youtube Data API for handling videos. Please follow the steps below to enable the API and start using it. Cre
4 min read
Youtube Data API | Set-1
Google provides a large set of API's for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, Youtube Data API is very simple to use provides features like - Search for videosHandle videos like retrieve information about a video, insert a video, delete a video etc.Handle Subscriptions lik
5 min read
Youtube Data API | Set-2
Prerequisite: Youtube Data API | Set-1 In the previous article we have discussed first two variants of search method. Now let's discuss the remaining three- Search Live Events, Search Related Videos and Search My Videos. Search by Live Events: Given example retrieves top 5 live broadcasts associated with the query string Python Programming. type pa
6 min read
Youtube Data API for handling videos | Set-2
Prerequisite: Youtube Data API for handling videos | Set-1 We have recently discussed first two variants of video list method, Video List by Video Id and Video List by Multiple Video Ids. Now, let's discuss the other two variants - Video List Most Popular Videos Video List My Liked Videos List most popular videos: The regionCode parameter states th
6 min read
Youtube Data API for handling videos | Set-3
Prerequisite: Youtube Data API for handling videos | Set-1, Set-2Before proceeding further, first see how to get a list of valid Video Categories, to determine in which category to put a video. For the example we have used the "IN" value for the regionCode parameter. You can use any other value. Only categoryId's that have assignable parameter as v
7 min read
Youtube Data API for handling videos | Set-4
Prerequisite: Youtube Data API for handling videos | Set-1, Set-2, Set-3 In this article we will discuss two methods related to video: Update a Video, Delete a Video. Updating a video and deleting an uploaded video requires user's authorization, so we will be creating OAuth type of credential for this example. Follow the steps below to generate a C
7 min read
Youtube Data API for handling videos | Set-5
Prerequisite: Youtube Data API for handling videos | Set-1, Set-2, Set-3 In this article, we will be discussing Rate a Video and Get Rating of a Video. Examples in this article will be requiring user authorization. So, we will be first creating OAuth Credential and install additional libraries. Follow the steps below to generate a Client Id and a S
5 min read
Youtube Data API Playlist | Set-1
After covering all types of search and video methods, we will be discussing in this article about Playlist. Everyone must be knowing what playlist is in Youtube. There are two ways to retrieve the playlist using Youtube Data API: Retrieve all PlaylistRetrieve My Playlist We will discuss these methods in detail with full code and output. Follow the
8 min read
Youtube Data API Playlist | Set-2
We already have discussed first two methods for a Playlist - to list all Playlist associated with a Channel Id, To retrieve my Playlist i.e. playlist of authorized user's account. Now, we will be discussing three more methods: Insert a Playlist, Update a Playlist and Delete a Playlist. This means we can just use the API to insert or we can say crea
11 min read
Youtube Data API Playlist | Set-3
From the previous article, we have seen that API can be used to insert, update or delete a playlist. Now the question comes that once we have created a playlist, do we have to go to Youtube and manually add the video to the newly created playlist. NO!!! all you have to do is use the OAuth Credential and just know the playlist Id to add the video to
8 min read
Youtube Data API Playlist | Set-4
In the last article, we discussed how to list the contents of the desired playlist and how to insert a video in a playlist. Now, in this article, we will be discussing how to update a video in the desired playlist and how to delete the video. So starting with the Updating a video, Let's quickly discuss how to get a Client Id and a Secret Key. Go to
8 min read
Youtube Data API Subscription | Set-1
In this article, we will be discussing about the Youtube Subscriptions. How API can be used to retrieve and manipulate these subscriptions. There are three operations that we will be discussing: List all the subscriptions associated with a Youtube channel Insert a new subscription Delete a subscription. All these methods will be requiring user's au
5 min read
Youtube Data API Subscription | Set-2
Prerequisite: Youtube Data API Subscription | Set-1 Now we will be discussing remaining two methods to list subscriptions i.e. to list subscriptions for authorized user's account and to check whether a subscription exists or not. Code to list subscriptions for authorized user's account: This example shows how to retrieve the list of subscriptions a
6 min read
Youtube Data API Subscription | Set-3
In the previous articles Youtube Data API Subscription | Set 1, Set 2 we have discussed three methods- To retrieve the list of subscriptions associated with a channel Id To retrieve my subscriptions i.e. associated with authorized user's account To check whether a subscription exist or not. In this article we will be discussing following two method
8 min read
How to Extract Wikipedia Data in Python?
In this article we will learn how to extract Wikipedia Data Using Python, Here we use two methods for extracting Data. Method 1: Using Wikipedia module In this method, we will use the Wikipedia Module for Extracting Data. Wikipedia is a multilingual online encyclopedia created and maintained as an open collaboration project by a community of volunt
5 min read
Extract Data from Database using MySQL-Connector and XAMPP in Python
Prerequisites: MySQL-Connector, XAMPP Installation A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. RequirementsXAMPP: Database / Server
2 min read
How To Extract Data From Common File Formats in Python?
Sometimes work with some datasets must have mostly worked with .csv(Comma Separated Value) files only. They are really a great starting point in applying Data Science techniques and algorithms. But many of us will land up in Data Science firms or take up real-world projects in Data Science sooner or later. Unfortunately in real-world projects, the
6 min read
How to Extract Weather Data from Google in Python?
In this article, we will see how to extract weather data from google. Google does not have its own weather API, it fetches data from weather.com and shows it when you search on Google. So, we will scrape the data from Google, and also we will see another method to fetch a schematic depiction of a location's weather data for the next two days in Pyt
4 min read
Extract Data from PGN Files Using the Chess Library in Python
In this article, we are going to see how to extract data from PGN Files using the chess library in Python. With the help of the chess library in python, we can perform several operations like validating a move, extracting data, and even making moves on the chessboard. In this article, we will extract data from a PGN file or a PGN string using the p
6 min read
How to extract Time data from an Excel file column using Pandas?
Prerequisite: Regular Expressions in Python In these articles, we will discuss how to extract Time data from an Excel file column using Pandas. Suppose our Excel file looks like below given image then we have to extract the Time from the Excel sheet column and store it into a new Dataframe column. For viewing the Excel file Click Here. Approach: Im
2 min read
How to extract the data from an ImmutableMultiDict
Perquisites : ImmutableMultiDict In this article, we are going to use ImmutableMultiDict to extract the data using Python, which is a type of Dictionary in which a single key can have different values. It is used because some form elements have multiple values for the same key and it saves the multiple values of a key in form of a list. Examples 1:
1 min read
Extract Dictionary Value from Column in Data Frame
Data Frames in Python, especially with libraries like Pandas, are powerful tools for data manipulation and analysis. Sometimes, data stored within a Data Frame's column may be in the form of dictionaries. Extracting values from such dictionaries is a common operation in data preprocessing. This post explores various methods to extract dictionary va
3 min read
YouTube Media/Audio Download using Python - pafy
This tutorial will help you download youtube video or audio with python using pafy library. Pafy library is used to retrieve YouTube content and metadata. Features of Pafy (i) Retrieve metadata such as viewcount, duration, rating, author, thumbnail, keywords. (ii) Download video or audio at requested resolution / bitrate / format / filesize (iii) C
2 min read
Python - Downloading captions from YouTube
Python provides a large set of APIs for the developer to choose from. Each and every service provided by Google has an associated API. Being one of them, YouTube Transcript API is very simple to use provides various features. In this article, we will learn how to download captions or subtitles from a YouTube video. The subtitles can be auto-generat
6 min read
Python | Program to download complete Youtube playlist
Python is a multi-purpose programming language and is widely used for scripting small tasks. Let's see how to make your own Youtube Playlist Downloader using Python. Though there are many software available in the market but making your own serving that purpose is quite a learning and impressive as well. Modules needed: BeautifulSoup bs4PyQt5PyQtWe
3 min read
Python | Download YouTube videos using youtube_dl module
Each and every day, you must be watching some video or another on YouTube which may be related to Music, Movies, Studies, Research, Leisure etc. You might want to store some video for future use where it will be required due to lack of internet or saving data or any other reason. What if we tell you that you can do this exact very thing using Pytho
1 min read