Can you Play a Youtube video using Playwright?

336 views Asked by At

Just for educational purposes, is there a way to do it?

I ran:

playwright codegen demo.playwright.dev/todomvc

and got these:

page.locator("video").click()
page.get_by_label("YouTube Video Player").click()
page.get_by_label("Play keyboard shortcut k").click()

But it doesn't work.

1

There are 1 answers

0
ggorlen On

One option is to use the keyboard shortcut k:

from playwright.sync_api import sync_playwright  # 1.37.0


with sync_playwright() as p:
    browser = p.chromium.launch(headless=False)
    page = browser.new_page()
    page.goto("https://www.youtube.com/watch?v=5mGuCdlCcNM")
    page.keyboard.press("k")
    input("press any key to exit")

This may seem roundabout, but YouTube can change DOM elements any time, but probably won't change their user-facing keyboard shortcuts used by millions. It's a good thing to avoid CSS selectors in most cases. Even labels and clicks can be unstable.

For future reliability, the main factor is making sure the keyboard key isn't triggered before the page loads and relevant listeners are ready. At the time of posting, however, the above code seems consistent without adding a delay.