Using the requests
and BeautifulSoup
libraries to scrape YouTube search results:
This script searches YouTube for the given query, extracts the titles and URLs of the search results, and prints them out. Make sure to install the requests
and beautifulsoup4
libraries if you haven't already:
pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
def scrape_youtube(query):
url = f"https://www.youtube.com/results?search_query={query}"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
# Extracting video titles and URLs
videos = soup.find_all('a', class_='yt-uix-tile-link')
for video in videos:
title = video['title']
url = 'https://www.youtube.com' + video['href']
print(f"Title: {title}\nURL: {url}\n")
# Example usage
query = "python web scraping tutorial"
scrape_youtube(query)
If you find this code useful don't forget to comment
Comments
Post a Comment