rpb
rpb

Reputation: 3299

Unable to play YouTube video using Selenium with Python

Spec: Chrome: Version 81.0.4044.113 (Official Build) (64-bit)

I would like to play HTML video by using Selenium. The link to the video can be accessed from:

https://www.youtube.com/watch?v=nXbfZL5kttM

The closes thread that addressing this problem can be found online such as OP1.

Based on the suggestion provided by RP1, the following code were drafted:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


chrome_options = webdriver.ChromeOptions()
browser = webdriver.Chrome(executable_path=r"Browsers\chromedriver.exe",
                           options=chrome_options)
browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")
WebDriverWait(browser, 40).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@src='https://www.youtube.com/watch?v=nXbfZL5kttM']")))
WebDriverWait(browser, 40).until(EC.element_to_be_clickable((By.XPATH, "//button[@class='ytp-large-play-button ytp-button']"))).click()

However, Selenium throw an error at line : WebDriverWait(browser, 40).until(EC.frame_to_be_available_and_switch_to_it.

Unable to locate element: {"method":"xpath","selector":"//iframe[contains(@src,'https://www.youtube.com')]"}

Or as per RP2:

required_frame = browser.find_element_by_xpath("//iframe[contains(@src,'https://www.youtube.com')]")
browser.switch_to.frame(required_frame)
element = browser.find_element_by_xpath("//button[@aria-label='Play']")
element.click()

Similarly, a similar error was thrown at line browser.find_element_by_xpath.

Are there possibilities that YouTube had changed their framework (e.g., iframe) that lead the previous suggestion not working anymore? I try to check all available iframe as suggested from this OP3, but I am a bit clueless on how to find the correct iframe suitable for my case.

I appreciate for any help.

Edit 1:

As suggested by OP4:

video = browser.findElement(By.id("id video")) # Use the id of the video to find it.
video.click()

No error, but the video not playing.

Upvotes: 1

Views: 4693

Answers (1)

Ratmir Asanov
Ratmir Asanov

Reputation: 6459

You don't need to locate the iframe, there is no such one. So, your code should look like this:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


browser = webdriver.Chrome()
browser.get("https://www.youtube.com/watch?v=nXbfZL5kttM")

WebDriverWait(browser, 15).until(EC.element_to_be_clickable(
    (By.XPATH, "//button[@aria-label='Play']"))).click()

I hope it helps you!

Upvotes: 1

Related Questions