2016-08-23 24 views

回答

0
driver.get("http://www.google.com"); 
WebElement ele = driver.findElement(By.id("hplogo")); 

//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 eleWidth = ele.getSize().getWidth(); 
int eleHeight = ele.getSize().getHeight(); 

//Crop the entire page screenshot to get only element screenshot 
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(), eleWidth, 
    eleHeight); 
ImageIO.write(eleScreenshot, "png", screenshot); 

//Copy the element screenshot to disk 
File screenshotLocation = new File("C:\\images\\GoogleLogo_screenshot.png"); 
FileUtils.copyFile(screen, screenshotLocation); 

摘自here

1

有沒有內置的方式來與Intern做到這一點。 takeScreenshot方法只需調用Selenium的屏幕截圖服務,該服務將整個頁面的屏幕截圖作爲base-64編碼的PNG返回。在將結果交給用戶之前,實習生的takeScreenshot將其轉換爲節點緩衝區。

要裁剪圖像,您需要使用外部庫或工具,例如png-crop(請注意,我從來沒有使用過)。該代碼可能看起來像下面(未經測試):

var image; 
var size; 
var position; 

return this.remote 
    // ... 
    .takeScreenshot() 
    .then(function (imageBuffer) { 
     image = imageBuffer; 
    }) 
    .findById('element') 
    .getSize() 
    .then(function (elementSize) { 
     size = elementSize; 
    }) 
    .getPosition() 
    .then(function (elementPosition) { 
     position = elementPosition; 
    }) 
    .then(function() { 
     // assuming you've loaded png-crop as PNGCrop 
     var config = { 
      width: size.width, 
      height: size.height, 
      top: position.y, 
      left: position.x 
     }; 
     // need to return a Promise since PNGCrop.crop is an async method 
     return new Promise(function (resolve, reject) { 
      PNGCrop.crop(image, 'cropped.png', config, function (err) { 
       if (err) { 
        reject(err); 
       } 
       else { 
        resolve(); 
       } 
      }); 
     }); 
    }) 
+0

謝謝,我會使用像WebdriverCSS這樣能夠做我需要的東西。 – scosmaa

+0

有趣的是,我沒有看到WebDriverCSS。我們實際上正在爲Intern開發一個可視化迴歸測試更新,所以這種類型的操作在未來可能會變得更容易一些。 – jason0x43

+0

如何導入實驗室測試模塊中的node.js模塊(PNGCrop)? – Shrike