请问如何用Selenium的WebDriver 截图来截取一个iframe?

2024-12-29 12:56:05
推荐回答(1个)
回答1:

webdriver没有现成的,自己写一个。代码如下,可以截任何一个WebElement,Good Luck!

import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;

public class Shooter{

private WebDriver driver;

public void shootWebElement(WebElement element) throws IOException {

File screen = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE);

Point p = element.getLocation();

int width = element.getSize().getWidth();
int height = element.getSize().getHeight();

Rectangle rect = new Rectangle(width, height);

BufferedImage img = null;

img = ImageIO.read(screen);

BufferedImage dest = img.getSubimage(p.getX(), p.getY(), rect.width,
rect.height);

ImageIO.write(dest, "png", screen);

File f = null;

f = new File("D:\\one\\where\\over\\the\\rainbow");

FileUtils.copyFile(screen, f);

}
}