Below is a piece of code which
1. navigates thru some craigslist pages
2. Takes a image screenshot and save it to a file
3. Saves the source code into a file
4. Pauses briefly for user to review the page

 



import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.*;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;

public class recom {
public static void main(String[] args) throws Exception {

WebDriver driver = new FirefoxDriver();

driver.get("http://sfbay.craigslist.org");
WebElement element = driver.findElement(By.linkText("software / qa / dba"));
element.click();

(new WebDriverWait(driver, 10)).until(new ExpectedCondition() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("sf");
}
});

element = driver.findElement(By.name("query"));
element.sendKeys("selenium");
element.submit();

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\users\\Public\\screenshot.png"));
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\users\\Public\\test.txt"));
out.write(driver.getPageSource());
Thread.sleep(5000);
driver.quit();
}
}

 

 

Thank you: https://salji.wordpress.com/2011/10/20/selenium-example-which-takes-screenshot-as-well-the-source-code/