How can I capture a screenshot using HtmlUnitDriver? I found that i can capture when I use FirefoxDriver but I don't want to use Firefox. So, please let me know how to capture images using HtmlUnitDriver.
I googled but none of the solutions I found are working for me. Please help!
Flyingsaucer is a java library which lets you take screenshots of a webpage headlessly (without opening the page in a browser). The following code will capture a screenshot of the entire page resized into an image called "screenshot.png". The number 1024 specifies the width of the output screenshot. Find the libraries here http://mvnrepository.com/artifact/org.xhtmlrenderer
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import org.xhtmlrenderer.simple.Graphics2DRenderer;
public class RenderPage {
public static void main(String[] args) throws Exception {
try {
String address = "http://www.w3.org";
BufferedImage buff = Graphics2DRenderer.renderToImageAutoSize(address, 1024);
ImageIO.write(buff, "png", new File("screenshot.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can also use the method Graphics2DRenderer.renderToImage(address,1024,1024); to define your own size of screenshot.
You'll find that the screenshots look as if they were rendered on a phone. I don't know why this is, but I'm guessing that you can change Flyingsaucer's browser version somewhere to emulate the page on different browsers.
One more thing is that this code won't screenshot www.google.com but apparently this type of error can be solved by tidying up the page source with a library called JTidy.
HtmlUnitDriver is GUI-less.
see: here
Maybe you can use the following:
BufferedImage image = new Robot().createScreenCapture(newRectangle(Toolkit.getDefaultToolkit().getScreenSize()));
ImageIO.write(image, "png", new File("/screenshot.png"));
source
Related
I am doing the automation for the application. I want to open the application/web page and try to take capture the screen. But I am facing the issue while doing the same. I am using the Robot class of java to capture the screen. My problem is
Before the application opens, the screen capture function is called which doesn't include the application window I want
Same issue for the web page. Before web page fully loaded, screen shot is taken.
I don't want any hard delay (i.e sleep(2000)). I want to add smart delay for both of the cases. Can somebody help me with this issue? Here is the sample code.
I have already tried it with hard delay but it is working in some cases and not in some. It is hard to predict the exact delay for web page to load.
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.File;
import javax.imageio.ImageIO;
public class Screenshot
{
public static void main(String[] args)
{
try
{
Runtime.getRuntime().exec("calc");
Robot robot = new Robot();
Thread.sleep(200);
String path = "D:// calc.jpg";
Rectangle capture = new
Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage Image = robot.createScreenCapture(capture);
ImageIO.write(Image, "jpg", new File(path));
System.out.println("Screen Captured);
}
catch (IOException | InterruptedException ex)
{
System.out.println(ex);
}
}
}
It should wait till calc window open and then take the screen shot. Now it depends on the system load how much time the calc window take to open. Same for the web page. I want a smart delay to wait until the application/web page open.
I am trying to take screenshot of the table given in one webpage. and the same element xpath I am providing in the code however Ashot code is capturing screenshot of some other location.
I have also tried other code of taking screenshot,
Screenshot screenshot = new AShot().takeScreenshot(driver,driver.findElement(By.xpath(webElementXpath)));
but it was giving me error which I was able to fix by reading this link: https://github.com/pazone/ashot/issues/93 and then I used below code:
WebElement myWebElement = driver.findElement(By.xpath("//center/table/tbody/*"));
Screenshot fpScreenshot = new AShot()
.coordsProvider(new WebDriverCoordsProvider()).takeScreenshot(driver,myWebElement);
ImageIO.write(fpScreenshot.getImage(),"PNG",new File("/Users/sanatkumar/eclipse-workspace/com.ScreenshotUtility/Screenshots/error.png"));
Please help as this code is giving me the screenshot of some random part of the webpage. I tried to capture other element as well but again I did not get the correct screenshot:
Please note my table is not fully visible on the webpage, manually I have to scroll down to view full table. do I need to write other code to get full screenshot of the table??
also my website is angular based which I am trying to automate using selenium java. the reason why I am doing this is because in protractor I dint find any API like Ashot. if anybody knows about it please let me know.
By adding a shootingStrategy I was able to capture just the form element with the attribute id = "post-form" at the bottom of this page.
From the documentation at https://github.com/pazone/ashot
Different WebDrivers take screenshots differently. Some WebDrivers
provide a screenshot of the entire page while others handle the
viewport only.
...
There are built-in strategies in ShootingStrategies for different use cases.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import ru.yandex.qatools.ashot.AShot;
import ru.yandex.qatools.ashot.Screenshot;
import ru.yandex.qatools.ashot.shooting.ShootingStrategies;
import javax.imageio.ImageIO;
import java.io.File;
public class Main
{
public static void main(String args[]) throws Exception
{
System.setProperty("webdriver.gecko.driver", "./geckodriver");
System.setProperty("webdriver.firefox.bin", "/usr/bin/firefox");
WebDriver driver = new FirefoxDriver();
driver.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
Thread.sleep(2000);
WebElement webElement = driver.findElement(By.id("post-form"));
Screenshot screenshot = new AShot().shootingStrategy(ShootingStrategies.viewportPasting(100)).takeScreenshot(driver,webElement);
ImageIO.write(screenshot.getImage(),"PNG",new File("/home/dan/ElementScreenshot.png"));
Thread.sleep(2000);
driver.quit();
}
}
Outputs:
This functionaity is possible with Protractor also by requiring an NPM module like 'protractor-image-comparison'. If you wanted to capture the related posts on the sidebar for instance you could use the following code.
Note: I haven't tested this package out with large elements that extend past the range of the browser viewport so can't say how they will work on those.
Spec File
describe('simple test', () => {
it('will save image', async () => {
await browser.get("https://stackoverflow.com/questions/54724963/ashot-is-not-taking-screenshot-of-correct-element");
await browser.driver.sleep(10 * 1000);
let related_questions_sidebar = element(by.className('module sidebar-related'));
await browser.executeScript('arguments[0].scrollIntoView();', related_questions_sidebar);
await browser.driver.sleep(3 * 1000);
// saveElement
await browser.protractorImageComparison.saveElement(related_questions_sidebar, 'sidebar-image');
});
});
Conf.js- in your OnPrepare
onPrepare: async () => {
// await jasmine.getEnv().addReporter(new dbReporter());
const protractorImageComparison = require('protractor-image-comparison');
browser.protractorImageComparison = new protractorImageComparison(
{
baselineFolder: './screen-compare/baselines/',
screenshotPath: './screen-compare/screenshots/'
}
);
);
Image Saved
Does anybody know how to make full screenshot of display using webdriver?
In Selenium documentation I read that it is possible: (http://selenium.googlecode.com/git/docs/api/java/org/openqa/selenium/TakesScreenshot.html)
..
The screenshot of the entire display containing the browser
..
I use Selenium Grid. My hub is on linux and node on windows. I tried to use Robot, however it takes screenshot on linux, however needs on windows
If you want a screenshot of your currently running browser instance then you can do it using following code:
public static void captureScreen(WebDriver driver, String screenshotFileName)
{
String screenshotsFile = screenshotsFolder+screenshotFileName+imageExtention;
try {
File screenShot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenShot, new File(screenshotsFile));
} catch (IOException e) {
}
}
But if you want to take screenshot of your active window (other than browser only) then you can use Robot class.
Edit:
Although it's too late for you, the link below contains your answer. I think it may be helpful for others who are searching for the same thing.
Screen shot issue in selenium webdriver
You need to use FirefoxDriver to screenshot whole page.
Chrome and IE doesn't support it.
hi try it like below it will take the complete webpage screen shot
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//The below method will save the screen shot in defined drive with name "screenshot.png"
FileUtils.copyFile(scrFile, new File("yourPath\\screenshot.png"));
I am trying to create a program that whenever I run it, it takes a screenshot of Google Chrome. So far, I have figured out how to have it take a screenshot and write it to a file. However, this is just a screenshot of the entire screen. I'd like to take a screenshot of chrome, even if it is just running in the background. Also, I'd like to be able to re-size Google Chrome and run the program to get images with the same dimensions as Google Chrome.
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.AWTException;
import java.awt.Rectangle;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
public class ProgramDriver {
public static void main(String[] args) {
Rectangle windowScreen = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
try {
BufferedImage capture = new Robot().createScreenCapture(windowScreen);
ImageIO.write(capture, "png", new File("screenshot.png"));
} catch (AWTException | IOException e) {
e.printStackTrace();
}
}
}
One way is to use image processing/recognition and recognize a distinctive symbol in your browser.
The other way is to go to the operating system and get the attributes where the window is etc
The third approach is to go with your mouse and check the coordinates/and size "ah now its there" and enter the coordinates into your program, "ah now its there..."
In effect you need the upper left coordinates and the size - any way you can get it
You can put up another question depending on which way you want
I am using IP Webcam APP for android and it is streaming MJPEG video through the local url :
http://192.168.0.2:8080/video
I was able to show the video using VLC player and this piece of code in C++.
On the OpenCV 2.2 I opened the url using:
VideoCapture cap;
cap.open("http://192.168.0.2:8080/video?dummy=param.mjpg");
It worked in C++, but I want it to work in Java. I was able to run OpenCV2.4.9 using Java when taking pictures from my built in webcam. This is my code for taking the images from a url in Java.
System.loadLibrary("opencv_java249");
VideoCapture capture = new VideoCapture();
capture.open("http://192.168.0.2:8080/video?dummy=param.mjpg");
But the capture.open does not open the streaming and I could not debug it properly. I know that it might be a issue with the ffmpeg, since it works on OpenCV2.2. I also know that my OpenCV2.2 is specific for MS 2010 and might be more complete.
Would it help if I compile the OpenCV2.4.9 from sources? Is there a file that I could add to solve that problem? Is there another way of receiving the video from the IP camera and using on OpenCV?
I took a while to figure it out. I could not receive the stream directly from OpenCVJava.I downloaded
http://www.mediafire.com/download/ayxwnwnqv3mpg39/javacv-0.7-bin.zip http://www.mediafire.com/download/2rkk0rjwxov7ale/javacv-0.7-cppjars.zip
Which I believe to be a java wrapper into OpenCV in C. I took this link from this video.
htttp://www.youtube.com/watch?v=mIYaHCyZICI
After unziping the zip I added the jars into my project and Used this code:
package javaapplication7;
import java.io.IOException;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
public class JavaApplication7 {
public static void main(String[] args) throws Exception {
OpenCVFrameGrabber grabber = new OpenCVFrameGrabber("http://192.168.0.2:8080/video?dummy=param.mjpg");
grabber.setFormat("mjpeg");
grabber.start();
for (int k=0; k<20000; k++){
System.out.print(k);
}
IplImage frame = grabber.grab();
CanvasFrame canvasFrame = new CanvasFrame("Camera");
canvasFrame.setCanvasSize(frame.width(), frame.height());
while (canvasFrame.isVisible() && (frame = grabber.grab()) != null) {
canvasFrame.showImage(frame);
}
grabber.stop();
canvasFrame.dispose();
System.exit(0);
}
}
Which I got from:
htttp://stackoverflow.com/questions/14251290/cvcreatefilecapture-error-could-not-create-camera-capture-with-javacv
It takes 15-20 seconds to start catching the streaming. But I was impressed with the delay which is much smaller than VLC. It is 1-2 seconds comparing to 3-4 seconds on VLC. I would like to upvote the guy who I took the answer from but I dont have enough reputation/
I also bumped into the same problem as you but the easiest method i figured out was to use droid cam instead of the Ip webcam app.Check it out here