Arthur
Arthur

Reputation: 3

How can I play a youtube video [selenium]

I want to play/pause a YouTube video in my python script but driver.find_element_by_name("body").send_keys('keys.SPACE') does not work

As it does not work I'm using pyautogui.press("space") instead but I have to be in the page. Using the selenium method is it possible to send the key signal without having YouTube focused?

Upvotes: 0

Views: 7674

Answers (1)

Maxiboi
Maxiboi

Reputation: 160

You could try finding the video and using .send_keys('keys.SPACE') or .click() methods which can be performed even if you don't have that exact window focused

Here's my code. I found the video by id movie_player. The code opens the page, waits 10 seconds, plays the video and stops it after a second. Hope it helps

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

driver = webdriver.Chrome('/Users/Max/Desktop/Code/Selenium/chromedriver')
driver.get('https://www.youtube.com/watch?v=DXUAyRRkI6k')
# wait for the page to load everything (works without it)
for i in range(10):
    print(i)
    time.sleep(1)
video = driver.find_element_by_id('movie_player')
video.send_keys(Keys.SPACE) #hits space
time.sleep(1)
video.click()               #mouse click

Upvotes: 3

Related Questions