WebDriver進行屏幕截圖

jopen 11年前發布 | 88K 次閱讀 Selenium 測試工具 webdriver

 例: 打開百度首頁 ,進行截圖

    package com.example.tests;  
    import java.io.File;  
    import org.apache.commons.io.FileUtils;  
    import org.junit.*;  
    import org.openqa.selenium.*;  
    import org.openqa.selenium.ie.InternetExplorerDriver;  
    public class Selenium2 {  
        @Test  
        public void testTakesScreenshot() {  
            WebDriver driver = new InternetExplorerDriver();  
            driver.get("http://www.baidu.com");  
            try {  
                File srcFile = ((TakesScreenshot)driver).  
                        getScreenshotAs(OutputType.FILE);  
                FileUtils.copyFile  
                (srcFile,new File("d:\\screenshot.png"));  
            } catch (Exception e) {  
                e.printStackTrace();  
            }   
              driver.close();  
            }  
    }  

TakesScreenshot接口提供了getScreenshotAs()方法來捕捉屏幕。上面的例子中,我們指定了OutputType.FILE作為參數傳遞給getScreenshoAs()方法,告訴它將截取的屏幕以文件形式返回。

 

如果使用的是RemoteWebDriver() ,則方法應該如下

首先啟動selenium java -jar selenium-server-standalone-2.25.0.jar

    package com.example.tests;  
    import java.io.File;  
    import java.io.IOException;  
    import java.net.MalformedURLException;  
    import java.net.URL;  
    import org.apache.commons.io.FileUtils;  
    import org.junit.*;  
    import org.openqa.selenium.*;  
    import org.openqa.selenium.remote.*;  
    public class Selenium2 {  
        @Test  
        public void testRemoteWebDriverScreenShot() {  
            //指定使用的瀏覽器  
            DesiredCapabilities capability = DesiredCapabilities.internetExplorer();  
            WebDriver driver = null;  
            try {  
                driver = new RemoteWebDriver( //我使用localhost來測試  
                        new URL("http://localhost:4444/wd/hub"), capability);  
            } catch (MalformedURLException e) {  
                e.printStackTrace();  
            }  
            driver.get("http://www.sina.com.cn");  
            //對遠程系統進行截圖  
            driver = new Augmenter().augment(driver);   
            File scrFile =    
              ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);  
            try {  
                FileUtils.copyFile(scrFile, new File("D:\\screenshot.png"));  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
    }  

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!