如何才能以最佳方式在 Selenium 2 中對測試進行截圖?
我們可以在 Selenium webdriver 中對測試進行截圖。捕捉截圖是故障分析中至關重要的一步。這是一個三步驟的過程。
首先,我們將 webdriver 物件轉換為名為 TakeScreenshot 的介面。然後需要使用 getScreenshotAs 方法來捕捉影像。要捕捉的影像的檔案格式作為引數傳遞給該方法。
最後,將捕捉到影像的檔案使用 FileUtils.copyFile 方法複製到一個位置。
語法
File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(s, new File("Image.png"));
示例
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.apache.commons.io.FileUtils; import java.io.File; public class ScreenshotImg{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://tutorialspoint.tw/index.htm"); //capture screenshot File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(s, new File("Img.png")); driver.quit(); } }
廣告