Open In App

Search and Play Youtube Music with Selenium using java

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article we will be playing music from YouTube Music is a music sharing website which is similar to Spotify created by Google. In this article we will be playing a song from YouTube Music using Google Chrome by Selenium and Java.

Example to Search and Play YouTube Music with Selenium using java

Here is an example to Search and Play YouTube Music with Selenium using java:

SimpleYouTubePlayer.java
package seleniumpractice;

import java.util.Scanner;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;

public class SimpleYouTubePlayer {

    public static void main(String[] args)
    {
        // Set the path for the ChromeDriver executable
        // manually
        System.setProperty(
            "webdriver.chrome.driver",
            "path/to/chromedriver"); // Replace with your
                                     // actual path

        // Initialize ChromeDriver
        WebDriver driver = new ChromeDriver();

        // Ask the user to enter the song they want to play
        Scanner scanner = new Scanner(System.in);
        System.out.println(
            "Enter the name of the song or artist you want to play: ");
        String musicName = scanner.nextLine();

        // Open YouTube and search for the song
        driver.get(
            "https://www.youtube.com/results?search_query="
            + musicName);

        // Click on the first video from the search results
        WebElement firstVideo = driver.findElement(
            By.xpath("(//a[@id='video-title'])[1]"));
        firstVideo.click(); // Play the first video

        // Inform the user
        System.out.println("Playing: " + musicName);

        // Allow the video to play for a while (10 seconds)
        try {
            Thread.sleep(
                10000); // Adjust this duration as needed
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }

        // Close the browser after playing
        driver.quit();
        scanner.close(); // Close the scanner
    }
}

Output

output
Output of played the music song from YouTube Music

Conclusion

We have successfully played the music song from YouTube Music without any human interaction and fully automated with the help of Selenium and Java.


Article Tags :

Similar Reads