- author: Monkhaus
Building a Random Video Generator Using Python
Welcome back to another video! In this one, we demonstrate how to build a random video generator using Python scripts and YouTube videos.
Demo
Before diving into the implementation, let us quickly demonstrate how the script works. First, we pull every single video link from a YouTube channel and put them in a database. Then, we use another script to show a random video from the database. Here is an example below:
Implementation
To implement this script, we will create three files: one to get the videos from YouTube channel and put them in a database, another to choose a random video from the database, and a separate requirements file with all the necessary dependencies.
Getting the Videos
First, let us create a file called get_videos.py
. We will start by removing the previous database file and the get_videos.py
and show_video.py
files if they already exist. Then, we will add the following code to our new get_videos.py
file:
importrequestsimportjsonimportsqlite3# Replace with your own YouTube channel URLurl='https://www.youtube.com/c/mrbeast6000/videos'# Make a request to the pageresponse=requests.get(url)content=response.content.decode()# Extract YouTube initial data from the pagestart=content.index('window["ytInitialData"]')+len('window["ytInitialData"]')+3end=content.index('"responseContext"')-1data=json.loads(content[start:end])# Get channel ID, title, logo, and subscriberschannel_id=data['metadata']['channelMetadataRenderer']['channelId']channel_title=data['metadata']['channelMetadataRenderer']['title']channel_logo=data['metadata']['channelMetadataRenderer']['avatar']['thumbnails'][0]['url']subscribers=data['metadata']['channelMetadataRenderer']['subscriberCountText']['simpleText'].replace(' subscribers','')# Format and print channel informationsubscribers_count=int(subscribers.split()[0])iflen(subscribers.split())>1andsubscribers.split()[1]=='million':subscribers_count*=1000000eliflen(subscribers.split())>1andsubscribers.split()[1]=='thousand':subscribers_count*=1000print(f'Channel ID: {channel_id}\nChannel Title: {channel_title}\nChannel Logo: {channel_logo}\nSubscribers: {subscribers_count}')
This code will print the channel information that we need to extract the video data. Next, we need to get the videos from the channel. We will use a Python module called scrapetube
to scrape the video data and store it in a SQLite database.
First, ensure that you have installed the scrapetube
module by adding the following line to your requirements file and run pip install -r requirements.txt
to install it:
scrapetube==0.3.4
Then, add the following code to your get_videos.py
file to get the videos from the channel and store them in the database:
importrequestsimportjsonimportsqlite3fromdatetimeimportdatetimefromtypingimportListfromscrapetubeimportChannelScraper# Set up database connectionconn=sqlite3.connect('mydatabase.db')cursor=conn.cursor()# Store video data in a list of dictionariesvideos=[]scraper=ChannelScraper('mrbeast6000')scraper.get_videos()forvideoinscraper.videos:video_data={'url':video['url'],'id':video['id'],'title':video['title'],'thumbnail':video['thumbnail'],'view_count':video['view_count'],'date':datetime.strptime(video['date'],'%Y-%m-%d')}videos.append(video_data)# Create a table and insert video datacursor.execute('''CREATE TABLE IF NOT EXISTS videos ( id INTEGER PRIMARY KEY, url TEXT, video_id TEXT, title TEXT, thumbnail TEXT, view_count INTEGER, date TEXT)''')forvideoinvideos:cursor.execute('''INSERT INTO videos(url, video_id, title, thumbnail, view_count, date) VALUES(?,?,?,?,?,?)''',(video['url'],video['id'],video['title'],video['thumbnail'],video['view_count'],video['date'].strftime('%Y-%m-%d')))conn.commit()
Choosing a Random Video
Next, let us a create a file called show_video.py
. We will copy over the previous code that selects a video at random from the database and plays it.
importsqlite3importwebbrowserimportrandomconn=sqlite3.connect('mydatabase.db')cursor=conn.cursor()cursor.execute('SELECT * FROM videos')videos=cursor.fetchall()video=random.choice(videos)print(f'Channel: Mr.Beast\nVideo Title: {video[3]}\nURL: {video[1]+video[2]}')webbrowser.open(video[1]+video[2])
Conclusion
Now that we have both Python scripts functioning properly, we can use this random video generator to discover new and interesting content. We hope that you enjoyed this tutorial, and the code is available for further customization on GitHub. Please leave a like if you found this useful, and thank you for watching!