Capturing full screen shot of webpage content using selenium 3 webdriver - java

i am trying to take a full content screen shot of web page . but i am only getting view based screen shot with following code. browser is firefox i am using SELENIUM 3 web driver.
File scrFile5 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(scrFile5, new File("C:\\test.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
how i can achieve the same.

You may want to make use of RemoteWebDriver interface. Are you working with Firefox or IE? See below
File screenshotFile = null;
try {
// This checks to make sure we're not running an
// incompatible driver to take a screenshot (e.g.
// screenshots are not supported by the HtmlUnitDriver)
//the following line will throw a ClassCastException if the current driver is not a browser typed driver
RemoteWebDriver compatibleDriver = (RemoteWebDriver) driver;
screenshotFile = ((TakesScreenshot) compatibleDriver).getScreenshotAs(OutputType.FILE);
} catch (ClassCastException e) {
//this driver does not support screenshots.
// this should get logged as a warning -- this only means the driver cannot be of type RemoteWebDriver
} finally {
if (screenshotFile == null) {
System.out.println("This WebDriver does not support screenshots");
return; //get us outa here
}
}
try {
String pathString = "some path of your choice"
File path = new File(pathString);
if (!path.exists())
path.mkdirs();
stringPath.concat("/someFileName.png");
File newFileLocation = new File(pathString);
System.out.println("Full path to screenshot: " + newFileLocation.getAbsolutePath());
FileUtils.copyFile(screenshotFile, newFileLocation);
} catch (IOException e) {
e.printStackTrace();
}

It's an old problem with Selenium browser drivers.
Try this utility: aShot
You can find it at https://github.com/yandex-qatools/ashot

Related

Selenium FirefoxDriver print to pdf doesn't print background images although "background" is set to true in PrintOptions

I want to get a pdf of a webpage using selenium WebDriver. I'm using FirefoxDriver because ChromeDriver has trouble calculating exact A4 size which leaves a white line at the bottom. Printing works fine with FirefoxDriver except it does not include background images.
public boolean fromHTML(String url) {
System.setProperty("webdriver.gecko.driver", "src/main/resources/geckodriver");
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--headless", "--disable-gpu");
FirefoxDriver driver = new FirefoxDriver(options);
driver.manage().window().maximize();
driver.get(url);
PrintOptions printOptions = new PrintOptions();
printOptions.setBackground(true);
Pdf pdf = driver.print(printOptions);
try {
Files.write(Paths.get("./cert.pdf"), OutputType.BYTES.convertFromBase64Png(pdf.getContent()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return true;
}
FirefoxDriver gets print(PrintOptions options) from https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/class-use/PrintsPage.html

Need to throw error messages if path to an external app doesn't exist in Java

I have 4 jButtons that execute each specific program (Browsers for the time being), I need to make a conditional that tells a user that if a path to that specific program doesn't exist it will open a webpage with that specific browser in mind.
This piece of code repeats itself and I need to optimise it. I tried making another method where I would use if statement but instead it just gave me a lot of issues while executing each button.
Warning_MSG(); is just another method with jOptionPane to confirm if a user wants to open an external application, etc etc.
private void chromeMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");
if(!file.exists()){
try {
URI url = new URI("https://google.com/chrome");
java.awt.Desktop.getDesktop().browse(url);
System.err.println("File Error, Google Chrome is not found!\n");
} catch (IOException | URISyntaxException e) {
System.err.println("Unknown Error, Exception found\n" + e);
}
}else {
Warning_MSG(file);
}
}
private void firefoxMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Program Files\\Mozilla Firefox\\firefox.exe");
if(!file.exists()){
try {
System.err.println("File Error, Mozilla Firefox is not found!\n");
URI url = new URI("https://www.mozilla.org/en-GB/firefox/download/thanks/");
java.awt.Desktop.getDesktop().browse(url);
} catch (IOException | URISyntaxException e) {
System.err.println("Unknown Error, Exception found\n" + e);
}
}else {
Warning_MSG(file);
}
}
private void ieMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe");
if(!file.exists()){
System.err.println("File Error, iExplorer is not found! \n");
}else {
Warning_MSG(file);
}
}
private void edgeMouseClicked(java.awt.event.MouseEvent evt) {
File file = new File("C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdge.exe");
if(!file.exists()){
System.err.println("File Error, Microsoft Edge is not Found! \n");
}else {
Warning_MSG(file);
}
}
The question is, how can I optimise these pieces of code so that I don't have to repeat the same thing all over again with other programs but instead run certain things only when conditions are met?
You can create an enum with 2 parameters (exe path, download page)
enum Browser
{
Chrome("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", "https://google.com/chrome"),
Firefox("C:\\Program Files\\Mozilla Firefox\\firefox.exe", "https://www.mozilla.org/en-GB/firefox/download/thanks/"),
IExplorer("C:\\Program Files (x86)\\Internet Explorer\\iexplore.exe", "https://google.com/internet-explorer"),
Edge("C:\\Windows\\SystemApps\\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\\MicrosoftEdge.exe", "https://google.com/download-edge");
private final String _filePath, _downloadPageURL;
Browser(String filePath, String downloadPage)
{
_filePath = filePath;
_downloadPageURL = downloadPage;
}
private String getDownloadPageURL()
{
return _downloadPageURL;
}
private String getFilePath()
{
return _filePath;
}
public boolean exists()
{
return new File(getFilePath()).exists();
}
public void openDownloadPage()
{
try
{
Desktop.getDesktop().browse(new URI(getDownloadPageURL()));
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Then, all you have to do is a simple check at your methods.
private void chromeMouseClicked(java.awt.event.MouseEvent evt)
{
final Browser chrome = Browser.Chrome;
if (!chrome.exists())
{
chrome.openDownloadPage();
System.err.println("File Error, Google Chrome is not found!\n");
return;
}
// The browser exists at this line. So create your code
// ...
}

Browsermob doesn't intercept anything with Sauce Labs through Sauce Connect

I'm trying to switch from Browserstack to Sauce Labs (the former spawns a zombie process in docker which hangs up the whole container). And while everything seems to connect and listen to ports, the HAR is null.
My setup is straightforward: on the machine that's running the tests I launch both BMP and SC from my code. Then my test fires up a remote WebDriver which opens a web page (I use here Google just as an example). Then, this internet connection should be proxied through BMP so that I could capture all the analytics.
In my experience with BrowserStack that worked. However, in the very same setup with Sauce Labs, I don't get anything intercepted.
#BeforeClass
public void SetUp() {
SauceConnectFourManager = new SauceConnectFourManager(true);
browserMobProxyServer = new BrowserMobProxyServer();
browserMobProxyServer.setTrustAllServers(true);
browserMobProxyServer.start(9191);
browserMobProxyServer.enableHarCaptureTypes(CaptureType.REQUEST_CONTENT, CaptureType.RESPONSE_CONTENT);
try {
SauceConnectFourManager.openConnection(username, key,4445,
null, "-v --pac file://" + filePath,
null, false, null);
} catch (IOException e) {
e.printStackTrace();
}
DesiredCapabilities caps = DesiredCapabilities.chrome();
caps.setCapability("platform", "Windows 10");
caps.setCapability("version", "latest");
String url = "https://" + username + ":" + key + "#ondemand.saucelabs.com:443/wd/hub";
try {
driver = new RemoteWebDriver(new URL(url), caps);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void TestShouldPass() {
/**
* Goes to Google's page just as an example
*/
driver.get("https://google.com");
System.out.println("title of page is: " + driver.getTitle());
}
#AfterClass
public void TearDown() {
driver.quit();
SauceConnectFourManager.closeTunnelsForPlan(username, null, null);
//har is null here!
Har har = browserMobProxyServer.getHar();
FileOutputStream fos;
try {
fos = new FileOutputStream("debug.har");
har.writeTo(fos);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
browserMobProxyServer.stop();
}

Opening file using mPdfViewer.fromFile(file) shows an empty pdf

I'm having a problem with opening file using PDFViewer library.
Inside DocumentCreator class:
1. First I create the document using iText library and it works perfectly fine and it writes document to the given directory.
2. Then I create an object of a File to display it using PDFViewer.
try {
mDocument = new Document(); // new Document created
String path = "/" + FirebaseAuth.getInstance().getCurrentUser().getUid() + "-" + recipe.getTitle() + ".pdf";
String fullPath = Environment.getExternalStorageDirectory() + "/recipes" + path;
mPdfWriter = PdfWriter.getInstance(mDocument, new FileOutputStream(fullPath));
doTheWriting(recipe, activity);
Log.d("OK", "done");
mMyRecipeFile = new File(fullPath);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Inside same class (DocumentCreator) I created getter method for mMyRecipeFile.
public File getRecipeFile() {
return mMyRecipeFile;
}
After that in the DocumentTestFragment,
I created PDFView, called mPdfView, and I try to open this file.
mPdfView.fromFile(mDocCreator.getRecipeFile());
The problem is it is displaying an empty document, which is weird, because I opened Android Device Monitor, opened given file and it's not empty.
I found out what caused a problem. The thing is that I wrote:
PdfView.fromFile(file)
While proper form is
PdfView.fromFile(file).load();
It works just fine now.

Extent Report: Not able to see the screenshots on other machine

I am able generate the extent reports with screenshots on my local machine.
But when i mail the reports to someone else, or open the html on a differant machine, the screenshots are not visible. It says that the path is invalid.
While attaching the screenshot, i am giving the path of my local machine. And it is searching the same path on other machine too.
I tried zipping the html and pics in one folder too.
Please help me how to attach the screenshots into html file without local machine dependency.
You can do this by using base64 conversion of the obtained screenshots.
Use the following code in your framework and try it.
public static String addScreenshot() {
File scrFile = ((TakesScreenshot) BasePage.driver).getScreenshotAs(OutputType.FILE);
String encodedBase64 = null;
FileInputStream fileInputStreamReader = null;
try {
fileInputStreamReader = new FileInputStream(scrFile);
byte[] bytes = new byte[(int)scrFile.length()];
fileInputStreamReader.read(bytes);
encodedBase64 = new String(Base64.encodeBase64(bytes));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "data:image/png;base64,"+encodedBase64;
}
I faced same issue.
Share the folder in which you are storing the screenshots with everyone and return same path in below method.
public static String getScreenshot(WebDriver oDriver, String ScreenShotName) throws IOException
{
String dateName=new SimpleDateFormat("YYYYMMDDHHMMSS").format(new Date());
TakesScreenshot ts=(TakesScreenshot)oDriver;
File source=ts.getScreenshotAs(OutputType.FILE);
String destination=System.getProperty("user.dir")+"/FailedScreenshots/"+ScreenShotName+dateName+".png";
File finalDestination=new File(destination);
FileUtils.copyFile(source, finalDestination);
String Imagepath="file://Machinename/FailedScreenshots/"+ScreenShotName+dateName+".png";
return Imagepath;
}
Hope this helps!

Categories