Search and Play Youtube Music with Selenium in Python

Selenium WebDriver enables us to automate web browsers programmatically, making it possible to search and play YouTube music directly from Python scripts. This automation can streamline your music discovery process and integrate YouTube functionality into your applications.

Prerequisites

Before starting, ensure you have Python installed and a code editor ready. You'll also need to install Selenium and set up ChromeDriver for browser automation.

Installing Selenium

Install the Selenium library using pip ?

pip install selenium
Collecting selenium
  Downloading selenium-4.15.0-py3-none-any.whl (10.5 MB)
     |????????????????????????????????| 10.5 MB 1.2 MB/s
Installing collected packages: selenium
Successfully installed selenium-4.15.0

Setting Up WebDriver

Download ChromeDriver from the official website matching your Chrome version. Place it in your system PATH or specify its location directly.

Here's a basic WebDriver setup example ?

from selenium import webdriver
from selenium.webdriver.common.by import By
import time

# Initialize ChromeDriver
driver = webdriver.Chrome()

# Open YouTube
driver.get('https://www.youtube.com')
print("YouTube opened successfully")

# Close browser
driver.quit()
YouTube opened successfully

Searching for Music on YouTube

Create a function to search for specific songs using Selenium's element location methods ?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

def search_youtube_music(query):
    driver = webdriver.Chrome()
    driver.get('https://www.youtube.com')
    
    # Find search box and enter query
    search_box = driver.find_element(By.NAME, 'search_query')
    search_box.send_keys(query)
    search_box.send_keys(Keys.RETURN)
    
    # Wait for results to load
    time.sleep(3)
    
    # Get first few video titles
    video_titles = driver.find_elements(By.CSS_SELECTOR, '#video-title')
    
    print(f"Search results for '{query}':")
    for i, title in enumerate(video_titles[:3]):
        print(f"{i+1}. {title.get_attribute('title')}")
    
    driver.quit()

# Search for a song
search_youtube_music('Shape of You Ed Sheeran')
Search results for 'Shape of You Ed Sheeran':
1. Ed Sheeran - Shape of You (Official Video)
2. Shape of You - Ed Sheeran (Lyrics)
3. Ed Sheeran - Shape of You [Official Audio]

Playing Music Automatically

Automate video playback by clicking the first search result ?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time

def search_and_play_music(query):
    driver = webdriver.Chrome()
    driver.get('https://www.youtube.com')
    
    # Search for the song
    search_box = driver.find_element(By.NAME, 'search_query')
    search_box.send_keys(query)
    search_box.send_keys(Keys.RETURN)
    
    # Wait for results
    time.sleep(3)
    
    # Click first video result
    first_video = driver.find_element(By.CSS_SELECTOR, '#video-title')
    video_title = first_video.get_attribute('title')
    first_video.click()
    
    print(f"Now playing: {video_title}")
    
    # Wait for video to load and start playing
    time.sleep(5)
    
    # Keep browser open for 10 seconds to hear the music
    time.sleep(10)
    
    driver.quit()

# Search and play a song
search_and_play_music('Bohemian Rhapsody Queen')
Now playing: Queen - Bohemian Rhapsody (Official Video)

Complete YouTube Music Bot

Here's a more comprehensive example that combines search and playback functionality ?

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
import time

class YouTubeMusicBot:
    def __init__(self, headless=False):
        chrome_options = Options()
        if headless:
            chrome_options.add_argument('--headless')
        
        self.driver = webdriver.Chrome(options=chrome_options)
        self.driver.get('https://www.youtube.com')
        time.sleep(2)
    
    def search_music(self, query):
        search_box = self.driver.find_element(By.NAME, 'search_query')
        search_box.clear()
        search_box.send_keys(query)
        search_box.send_keys(Keys.RETURN)
        time.sleep(3)
        
        return self.get_search_results()
    
    def get_search_results(self):
        video_elements = self.driver.find_elements(By.CSS_SELECTOR, '#video-title')
        results = []
        
        for element in video_elements[:5]:
            title = element.get_attribute('title')
            if title:
                results.append(title)
        
        return results
    
    def play_first_result(self):
        first_video = self.driver.find_element(By.CSS_SELECTOR, '#video-title')
        first_video.click()
        time.sleep(3)
        return first_video.get_attribute('title')
    
    def close(self):
        self.driver.quit()

# Usage example
bot = YouTubeMusicBot()
results = bot.search_music('Imagine Dragons Believer')
print("Search Results:", results)

playing = bot.play_first_result()
print(f"Now playing: {playing}")

time.sleep(10)  # Let it play for 10 seconds
bot.close()

Key Points

  • Always use time.sleep() to wait for page elements to load
  • Use updated Selenium syntax with By.CSS_SELECTOR instead of deprecated methods
  • Handle browser closure with driver.quit() to free resources
  • Consider using headless mode for background automation

Conclusion

Selenium provides powerful automation capabilities for YouTube music interaction. You can search for songs, retrieve results, and automate playback using Python scripts. This approach enables building custom music bots and integrating YouTube functionality into larger applications.

Updated on: 2026-03-27T10:06:07+05:30

773 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements