create a function that gives you a random link to a youtube website in python

To create a function that gives a random link to a YouTube website, you can use the random, requests, and BeautifulSoup modules in Python. Here's an example:

main.py
import random
import requests
from bs4 import BeautifulSoup

def get_random_youtube_link():
    # Define the base URL and a list of possible characters for the video ID
    base_url = "https://www.youtube.com/watch?v="
    chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"

    # Generate a random video ID by choosing 11 random characters
    video_id = "".join(random.choice(chars) for i in range(11))

    # Build the full URL
    url = base_url + video_id

    # Use requests to fetch the HTML content of the page
    response = requests.get(url)
    html_content = response.text

    # Use BeautifulSoup to extract the title of the video
    soup = BeautifulSoup(html_content, "html.parser")
    video_title = soup.find("title").text.strip()

    # Return the title and URL as a tuple
    return (video_title, url)
845 chars
26 lines

In this function, we start by defining the base URL for YouTube video links, as well as a list of possible characters that can be used in the video ID.

Next, we use a for loop and the random.choice function to generate a random video ID by choosing 11 characters from the list of possible characters. We then append this video ID to the base URL to get the full URL for a random YouTube video.

We use the requests module to fetch the HTML content of this page, and then use BeautifulSoup to extract the title of the video. Finally, we return the title and the full URL as a tuple.

You can call this function as many times as you want to generate random YouTube links with each call.

gistlibby LogSnag