javascriptpython-3.xyoutubeweb-inspectorpython-webbrowser

Play YouTube video using webbrowser in python3


I want to play YouTube video using Python3. I can open the YouTube video using webbrowser.open(), but then i need to either press space or mouse click the play button to actually play the video. How to automate this, without using seleinum if possible.

        try:
        client = webbrowser.get("firefox")
        client.open("https://" + open_url)
    except webbrowser.Error as e:
        print(e)

In browser's console (inspect element), if I enter

document.querySelector('.ytp-play-button').click();

the video gets played, is there a way to simply pass this script (anyother alternative will also do the trick).

I am a student, and already know how to use selenium, and was just wondering if there is a simple was to do this one exact thing without selenium.

Oh yeah, when I simply copy past the url into chrome, or firefox tab than video gets played automatically without requiring me to press space or click the play button, if you know the answer to why this than please share it.

Thank you for your feedbacks.


Solution

  • You can play youtube videos using mpv. In the cmd you can play video Like This. Now using subprocess or os module you can run that command and play

    import os
    os.system(f"mpv https://www.youtube.com/watch?v=WNeLUngb-Xg")