Aayam Oza
Aayam Oza

Reputation: 56

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.

Upvotes: 1

Views: 5282

Answers (4)

NMB
NMB

Reputation: 1

You can use:

import webbrowser
webbrowser.open(url)
webbrowser.get(browser).open(url)

plus there are some other ways too.

Upvotes: 0

Monirul Islam
Monirul Islam

Reputation: 150

You can use pyautogui to press space

import time
import webbrowser
import pyautogui

try:
    client = webbrowser.get("firefox")
    client.open("https://" + open_url)
    time.sleep(30)       #give it a couple seconds to load
    pyautogui.press('space')
except webbrowser.Error as e:
    print(e)

Upvotes: 1

Mustafa Jablawi
Mustafa Jablawi

Reputation: 1

You can use

webbrowser.open_new(url)

Upvotes: 0

Utsav Patel
Utsav Patel

Reputation: 359

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")

Upvotes: 3

Related Questions