我正在尝试使用以下代码获取Gmail登录页面上“下一步”按钮的屏幕截图。
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("https://www.gmail.com");
WebElement signupButton= driver.findElement(By.xpath("//div[@id='identifierNext']"));
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage image = ImageIO.read(screenshot);
int width = signupButton.getSize().getWidth();
int height = signupButton.getSize().getHeight();
Rectangle rect = new Rectangle(width, height);
Point p = signupButton.getLocation();
BufferedImage dest = image.getSubimage(p.getX(), p.getY(), width, height);
ImageIO.write(dest, "png", screenshot);
FileUtils.copyFile(screenshot, new File("C:\\Users\\user\\Desktop\\Screenshots\\loginButton.png"));
拍摄的屏幕截图为空。图片中没有元素。
答案 0 :(得分:2)
您不再需要这样做。现在,在最新版本的Selenium中,您可以立即拍摄元素的屏幕快照,因为WebElement接口API已经具有该功能。看下面的例子:
element.getScreenshotAs(OutputType.BYTES)
答案 1 :(得分:0)
请您尝试以下代码
System.setProperty("webdriver.chrome.driver", "C:\\New folder\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://www.gmail.com");
WebElement ele = driver.findElement(By.xpath("//div[@id='identifierNext']"));
// Get entire page screenshot
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
BufferedImage fullImg = ImageIO.read(screenshot);
// Get the location of element on the page
Point point = ele.getLocation();
// Get width and height of the element
int windth = ele.getSize().getWidth();
int height = ele.getSize().getHeight();
// Crop the entire page screenshot to get only element screenshot
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),
windth, height);
ImageIO.write(eleScreenshot, "png", screenshot);
// Copy the element screenshot to disk
File screenshotLocation = new File("C:\\New folder\\Capture.png");
FileUtils.copyFile(screenshot, screenshotLocation);