WebDriver应用实例(java)——控制HTML5实现的视频播放器

        这个实例用于获取HTML5语言实现的视频播放器视频文件的地址、时长,控制播放器进行播放或暂停。

        被测试网页:http://www.w3school.com.cn/i/movie.ogg

package cn.om.TestHTML5;

import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;

public class TestHTML5VideoPlayer {

	WebDriver driver;
	String url;

	@Test
	public void testHTML5VideoPlayer() throws IOException, InterruptedException {
		// 定义页面截图文件对象,用于后面的屏幕截图存储
		File captureScreenFile = null;
		driver.get(url);
		System.out.println(driver.getPageSource());
		driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);

		// video对象放在iframe里,要先切换到iframe中,才能定位到video元素
		WebElement iframe = driver.findElement(By.xpath(".//*[@id='result']/iframe"));
		driver.switchTo().frame(iframe);
		WebElement videoPlayer = driver.findElement(By.tagName("video"));

		JavascriptExecutor js = (JavascriptExecutor) driver;
		// currentSrc属性获取视频文件的网络存储地址
		String videoSrc = (String) js.executeScript("return arguments[0].currentSrc;", videoPlayer);
		System.out.println(videoSrc);

		// 断言视频网络地址是否符合期望
		Assert.assertEquals("http://www.w3school.com.cn/i/movie.ogg", videoSrc);

		// duration属性获取视频文件的播放时长
		Double videoDuration = (Double) js.executeScript("return arguments[0].duration", videoPlayer);
		System.out.println(videoDuration.intValue());

		// 等待5秒让视频加载完成
		Thread.sleep(5000);
		// 使用JavaScript,调用播放器内部的play
		js.executeScript("return arguments[0].play()", videoPlayer);
		// 等待两秒,使用pause方法来暂停
		Thread.sleep(2000);

		js.executeScript("return arguments[0].pause()", videoPlayer);

		// 停顿3秒证明是否已暂停
		Thread.sleep(3000);

		captureScreenFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
		FileUtils.copyFile(captureScreenFile, new File("F:\\workspace\\WebDriver API\\2017-2-22\\videoPlay_pause.jpg"));

	}

	@BeforeMethod
	public void beforeMethod() {
		System.setProperty("webdriver.firefox.bin", "D:/Mozilla Firefox/firefox.exe");
		driver = new FirefoxDriver();
		url = "http://www.w3school.com.cn/tiy/t.asp?f=html5_video_all";

	}

	@AfterMethod
	public void afterMethod() {
		driver.quit();
	}

}

猜你喜欢

转载自blog.csdn.net/vikeyyyy/article/details/80225556