如何使用 Selenium Webdriver 捕獲特定元素的螢幕截圖,而不是整個頁面?
我們可以使用 Selenium webdriver 捕獲特定元素的螢幕截圖,而不是整個頁面。專案中可能有一些需求,我們需要捕獲特定 Web 元素的螢幕截圖。
首先,我們將捕獲整個頁面的螢幕截圖,然後根據元素的維度和位置進行裁剪。我們將藉助 TakeScreenShot 介面及其 getScreenshotAs 方法。
語法
File i = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
接下來,將圖片儲存在檔案中 [例如,.jpeg、.png]。
FileUtils.copyFile(i, new File("<<path of file>>"))
示例
程式碼實現
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 ElementScreenshot{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://tutorialspoint.tw/index.htm"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element WebElement m=driver.findElement(By.xpath( "//*[@title='Tutorialspoint']")); // full page screenshot capture File i = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); BufferedImage fl = ImageIO.read(i); //webelement location Point point= m.getLocation(); // webelement dimension int wd= m.getSize().getWidth(); int ht=m.getSize().getHeight(); // Crop Image to the element BufferedImage c= fl.getSubimage(point.getX(), point.getY(), wd, ht); ImageIO.write(c, "png", i); //copy screenshot to a file inside project folder FileUtils.copyFile(i, new File("logo.png")); driver.close(); } }
廣告