1

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.

Aayam Oza
  • 56
  • 1
  • 2
  • 8
  • Apperantly, I have to give firefox permission for autoplay on YouTube. But I am still not sure why opening YouTube video from python requires permission but directly entering url will autoplay the video. If you know the answer to this please share. – Aayam Oza Feb 17 '20 at 09:27
  • Because scripting isn't considered "interacted with the document first" since it can be automated. – Coreus Feb 03 '21 at 16:13

4 Answers4

3

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")
Utsav Patel
  • 319
  • 1
  • 5
  • 14
1

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)
Monirul Islam
  • 140
  • 1
  • 5
0

You can use

webbrowser.open_new(url)
trincot
  • 317,000
  • 35
  • 244
  • 286
0

You can use:

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

plus there are some other ways too.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
NMB
  • 1
  • 1