2026-11-06 · Q&A guide

Play and Verify Video with Selenium WebDriver in Java

Control video playback inside an iframe with Selenium WebDriver in Java, then capture a screenshot to confirm the video is playing.

Understanding iFrames

Many web pages embed videos inside an iframe to isolate the media player from the main document. Selenium can only interact with elements in the current DOM, so you must first switch the driver’s context to the iframe before you can click the play button.

Switching to the Video iFrame

Locate the iframe that contains the video and switch to it. Use a WebDriverWait to ensure the iframe is present and visible.

WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(20));
WebElement iframe = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("iframe[src*='video']")));
driver.switchTo().frame(iframe);

Locating and Clicking the Play Button

Once inside the iframe, find the play button. The button may be an SVG, a button element, or a custom div. Use a CSS selector that matches the visible control.

WebElement playBtn = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("button.play, .video-control.play")));
playBtn.click();

Pausing and Verifying Playback

To confirm the video started, wait for a change in the UI such as a pause icon appearing or the video’s currentTime increasing. A simple check is to compare the currentTime before and after a short pause.

JavascriptExecutor js = (JavascriptExecutor) driver;
long startTime = (long) js.executeScript("return document.querySelector('video').currentTime;");
Thread.sleep(2000);
long endTime = (long) js.executeScript("return document.querySelector('video').currentTime;");
if (endTime > startTime) {
    System.out.println("Video is playing.");
}

Taking a Screenshot

After confirming playback, switch back to the default content, locate the video container, and capture a screenshot. Store the image for evidence or comparison.

driver.switchTo().defaultContent();
WebElement videoContainer = driver.findElement(By.cssSelector("div.video-wrapper"));
File screenshot = videoContainer.getScreenshotAs(OutputType.FILE);
Files.copy(screenshot.toPath(), Paths.get("video_playback.png"));

Takeaway: Switching context to the iframe, clicking the play button, and capturing a screenshot ensures reliable video playback testing with Selenium.

People also ask

How do I handle multiple iframes on a page?

Iterate through all iframes using driver.findElements(By.tagName("iframe")) and switch to each until the target video is found.

What if the video is inside a shadow DOM?

Use JavaScript to pierce the shadow root: let shadow = document.querySelector('iframe').shadowRoot; then locate the video element within that root.

Inspired by a public discussion on Stack Overflow. This article is an original explanation for learners.

← All posts