web scrap from youtube in python

One way to scrape data from YouTube is by using the Beautiful Soup library in Python along with the Requests library.

Here's an example code snippet that extracts the title, description, and duration of the first video in a YouTube search result:

main.py
import requests
from bs4 import BeautifulSoup

query = "python web scraping" # replace with your search query
url = f"https://www.youtube.com/results?search_query={query}"
response = requests.get(url)
html = response.text
soup = BeautifulSoup(html, "html.parser")

# extract the first video element
first_video = soup.find("div", {"class": "yt-lockup-content"})

# extract the title, description, and duration of the first video
title = first_video.find("a", {"class": "yt-uix-tile-link"})["title"]
description = first_video.find("div", {"class": "yt-lockup-description"}).text.strip()
duration = first_video.find("span", {"class": "video-time"}).text.strip()

# print the extracted data
print("Title:", title)
print("Description:", description)
print("Duration:", duration)
775 chars
22 lines

This code uses the requests library to send a GET request to the YouTube search URL, and then uses Beautiful Soup to parse the HTML response and extract the relevant video data from the first search result. You can modify the query variable to search for different videos.

gistlibby LogSnag