How to extract youtube data in Python?
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 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).
- 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.
Code for main.py file :
Code for youtube_statistics.py file :
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.
- Import module
- Provide url of the channel whose data is to be fetched
- Extract data
- Display data fetched.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course