在自動化測試中常常會用到截圖功能诡延。最近用了一下selenium-webdriver的截圖功能還算不錯,可以截取頁面全圖锡凝,不管頁面有多長。
下面的代碼演示了如何使用webdriver進行截圖:
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class ShotScreen {
/**
* @author gongjf
* @throws IOException
* @throws InterruptedException
*/
public static void main(String[] args) throws IOException, InterruptedException {
System.setProperty("webdriver.firefox.bin","D:\\Program Files\\Mozilla Firefox\\firefox.exe");
WebDriver dr = new FirefoxDriver();
dr.get("http://www.51.com");
//這里等待頁面加載完成
Thread.sleep(5000);
//下面代碼是得到截圖并保存在D盤下
File screenShotFile = ((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenShotFile, new File("D:/test.png"));}}
看了一下OutputType接口和TakesScreenshot接口瞻讽,吐槽一下,貌似這兩個接口不是同一個開發(fā)寫的或者注釋沒有更新怎么的熏挎。在OutputType里面的注釋說:
/**
* Defines the output type for a screenshot. See org.openqa.selenium.Screenshot for usage and
* examples.
...
然后在那找了半天的org.openqa.selenium.Screenshot 接口速勇,暈,后來想應(yīng)該是org.openqa.selenium.TakesScreenshot坎拐。
在TakesScreenshot里有如下注釋:
/**
* Capture the screenshot and store it in the specified location.
*
* <p>For WebDriver extending TakesScreenshot, this makes a best effort
* depending on the browser to return the following in order of preference:
* <ul>
* <li>Entire page</li>
* <li>Current window</li>
* <li>Visible portion of the current frame</li>
* <li>The screenshot of the entire display containing the browser</li>
* </ul>
*
* <p><span style="color: #ff0000;">For WebElement extending TakesScreenshot, this makes a best effort
* depending on the browser to return the following in order of preference:
* - The entire content of the HTML element
* - The visisble portion of the HTML element</span>
*
* @param <X> Return type for getScreenshotAs.
* @param target target type, @see OutputType
* @return Object in which is stored information about the screenshot.
* @throws WebDriverException on failure.
*/
試了一下截取Webelement最終發(fā)現(xiàn)WebElement接口沒有實現(xiàn)這個類烦磁。搞了半天也只是會了截取頁面的全圖。截取當前的frame也截取的頁面全圖哼勇。難道這個功能沒有完善都伪,好吧,這樣說自我安慰一下积担。
selenium-webdriver 面向接口編程陨晶,找一個需要的功能還真是挺難的。