如何使用 Selenium WebDriver 部分截圖(幀)?
每當我們在測試過程中遇到故障時,一種常見的方式是在出現與預期結果偏差的位置拍攝螢幕截圖。因此,將螢幕截圖作為建立缺陷的附件被認為是一個必須的步驟。
在為大量測試用例執行自動化時,拍攝螢幕截圖對於推斷一個測試用例為何失敗(對於開發和測試團隊來說)至關重要。當他們對故障進行除錯時,查閱螢幕截圖並得出結論,故障是否是因為指令碼問題還是應用程式的缺陷。
有時,我們可能需要捕獲特定元素的螢幕截圖。在這裡,我們必須捕獲整個頁面的螢幕截圖,然後再根據元素的位置和尺寸對影像進行裁剪。
示例
程式碼實施。
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 java.io.File; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.Point; import java.awt.image.BufferedImage; public class ScrshtElemnt{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url ="https://tutorialspoint.tw/about/about_careers.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // identify logo WebElement l=driver.findElement(By.xpath( "//*[@class='top-logo']")); // capture screenshot and store the image File s = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); BufferedImage f = ImageIO.read(s); //location of webelement Point location= l.getLocation(); // Dimension of element int w= l.getSize().getWidth(); int h=l.getSize().getHeight(); // Image Crop BufferedImage cImage= f.getSubimage(location.getX(), location.getY(), w, h); ImageIO.write(cImage, "png", s); FileUtils.copyFile(s, new File("tutorialspointlogo.png")); driver.quit(); } }
輸出
廣告