import org.openqa.selenium.WebElement; //导入方法依赖的package包/类
public static void takeStatusScreenshot(Status status, MongoDatabase mongoDatabase, WebDriver driver) {
long id = status.getId();
User user = status.getUser();
try {
// visit the twitter url
driver.get(TWITTER_BASE_URL + user.getScreenName() + "/status/" + id);
WebDriverWait webDriverWait = new WebDriverWait(driver, 4);
webDriverWait.until(
ExpectedConditions.visibilityOfElementLocated(
By.cssSelector(PERMALINK_TWEET_CONTAINER)));
// Find the tweet container
WebElement element = driver.findElement(By.cssSelector(PERMALINK_TWEET_CONTAINER));
// take a full screenshot
File screenshotFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// create in memory image data
BufferedImage screenshotImage = ImageIO.read(screenshotFile);
// calculate the position of the tweet element
Point point = element.getLocation();
int elementWidth = element.getSize().getWidth();
int elementHeight = element.getSize().getHeight();
// crop to get only the container of the tweet itself (sometimes this doesn't work on mac)
BufferedImage elementScreenshotImage =
screenshotImage.getSubimage(
point.getX() + 4,
point.getY() + 4,
elementWidth - 4,
screenshotImage.getHeight() < point.getY() + elementHeight
? screenshotImage.getHeight() - 4
: elementHeight - 4);
ImageIO.write(elementScreenshotImage, "png", screenshotFile);
FileUtils.copyFile(screenshotFile, new File("screenshot/" + id + ".png"));
} catch (Exception e) {
saveFailureStatusProcesssed(mongoDatabase, id, false);
System.out.println(
String.format(
"Unable to create screenshot for %s with id: %d",
user.getScreenName(),
id));
e.printStackTrace();
}
}