Selenium WebDriver throwing TimoutException while invoking getScreenshotAs() - java

This is my code.
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "data/chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "logs/ss/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
}
All time when driver.get() throw TimeoutException I want to take a screenshot at browser.
But when throw TimeoutException, getScreenshotAs() from printSS() don't take screenshot because throw another TimeoutException.
Why getScreenshotAs() throw TimeoutException and how to take screenshot at browser
P.S.: Increase pageLoadTimeout time is not the answer I want.

While working with Selenium 3.x, ChromeDriver 2.36 and Chrome 65.x you need to mention the relative path of the location (with respect of your project) where you intend to store the screenshot.
I took you code and did a few minor modification as follows :
Declared driver as WebDriver instance as static and added #Test annotation.
Reduced pageLoadTimeout to 2 seconds to purposefully raise the TimeoutException.
Changed the location of String path to a sub-directory wthin the project scope as follows :
String path = "./ScreenShots/";
Added a log as :
System.out.println("Screenshot Taken");
Here is the code block :
package captureScreenShot;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class q49319748_captureScreenshot
{
public static WebDriver drive;
#Test
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "./ScreenShots/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
System.out.println("Screenshot Taken");
}
}
Console Output :
[TestNG] Running:
C:\Users\username\AppData\Local\Temp\testng-eclipse--153679036\testng-customsuite.xml
Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42798
Only local connections are allowed.
Mar 16, 2018 5:37:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Screenshot Taken
PASSED: test1
Screenshot :
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver

The problem is that while Selenium waits for the page to complete loading it cannot take any other command. This is why it throws TimeoutException also from the exception handler when you try take the screenshot.
The only option I see is to take the screenshot not through Selenium, but using other means that take a screenshot of the entire desktop. I've written such a thing in C#, but I'm pretty sure you can either find a way to do it in Java too.

Related

JMeter Java web driver sampler

I have the following Java code for a selenium web driver in JMeter:
package com.jmeter.test.scripts;
import java.io.File;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.OutputType;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.TakesScreenshot;
#Test
public class SnapScreenshot
{
String fileName = UUID.randomUUID.toString();
public static void main(String[] args)
{
System.setProperty("webdriver.chrome.driver", "C:\\Apache\\apache-jmeter-5.5\\Drivers\\Chrome\\109\\chromedriver.exe");
System.setProperty("webdriver.chrome.logfile", "C:\\Temp\\driverlog.log");
System.setProperty("webdriver.chrome.verboseLogging", "true");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("https://www.google.com/");
Thread.sleep(5000);
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
File destFile = new File("C:\\temp\\screenshots\\" + fileName + ".png");
try
{
FileUtils.copyFile(srcFile, destFile);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
driver.quit();
}
}
}
It doesn't appear to be executing:
The logfile is not created
Any System.out.println() statements I add are not executed
I'm also getting this error message: ERROR c.g.j.p.w.s.WebDriverSampler: unknown protocol: data
Not sure what I'm doing wrong. I do have the Chrome web driver configured via "jp#gc - Chrome Driver Config" but this doesn't seem to matter much.
If you're using the WebDriver Sampler you need to amend your code accordingly:
In the Chrome Driver Config specify the path to your chromedriver executable
Remove ChromeDriver instance initialization and use WDS.browser wherever you need to manipulate the browser
Switch to "groovy" language

Edureka - Handle exceptions in Selenium Web Driver - no print out

I am a total noob at Automation Testing and i am trying to learn through Youtube how to do it.
https://youtu.be/FRn5J31eAMw?t=12405
On this course from Edureka there is an example where they are trying to handle an exception, where after they run the script the system shows them a message in the console which i cannot get.
package co.edureka.selenium.demo;
import java.util.NoSuchElementException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class HandlingExceptions {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com");
Thread.sleep(3000);
try {
driver.findElement(By.name("fake")).click();
}catch (NoSuchElementException e) {
System.out.println("element is not found");
System.out.println("Hello");
//throw(e);
}
System.out.println("Hello");
}
}
this is the script in Java they are running and at the end in the console they are getting this as a result
Edureka Console
But i am getting something totally different even though my code is exactly the same.
My Console
What am i doing wrong?
your are using "import java.util.NoSuchElementException;
" at top of file so please remove and use below one
org.openqa.selenium.NoSuchElementException

opening chrome in selenium issue

I'm currently taking my first automated test class and the instructor has us creating a program in Eclipse after loading Selenium and create a step in the program to look at an executable to bring up chrome then designate a website to check. It looks like i am stuck in a loop?
Here is the program:
java program
Here is the result:
program result
any and all help would be appreciated. Thank you for your time.
I think this is what you want
This code is to open the default browser and go to a specific link
You can specify the path of any browser you want from the path in the code
import java.awt.Desktop;
import java.net.URI;
public class openBrowser {
public openBrowser() {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(new URI("https://www.google.com"));
}
}catch (Exception e) {
// TODO: handle exception
}
}
public static void main(String[]args) {
new openBrowser();
}
}
For your code you can follow the following steps
Download ChromeDriver from here
Extract the zip file and follow the path ( because it is easy ) C:\\chromeDriver\\chromedriver.exe
include the ChromeDriver location in your PATH environment variable
Download the required Libraries from the following junit openqa
Add the Libraries to your project ( Build Path )
then this is your code
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.*;
import org.junit.Test;
public class WebDriverDemo {
#Test
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:\\chromeDriver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://www.google.com/");
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("ChromeDriver");
searchBox.submit();
try {
Thread.sleep(10000);
} catch (InterruptedException ex) {
Logger.getLogger(WebDriverDemo.class.getName()).log(Level.SEVERE, null, ex);
}
driver.quit();
}
}
During the implementation of the code in the eclipse, many problems occurred, so I advise you to implement the project on NetBeans
I use Java 8 and Windows 8.1

Unable to start Chrome Driver in Selenium Webdriver 2

I am trying to open Chrome browser from Selenium webdriver but I'm failing to do so. At first I tried opening both Chrome and Firefox from the same program. The Firefox browser works perfectly fine, while I got error related to ChromeDriver exe file being not present. I downloaded the ChromeDriver file and added that to the External Jars and also called it using the System.setProperty( method.
Here is the original code:
package test.selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Selenium_test {
public static void main(String[] args) {
FirefoxDriver dr1=new FirefoxDriver();
FirefoxDriver dr2=new FirefoxDriver();
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
ChromeDriver dr3=new ChromeDriver();
ChromeDriver dr4=new ChromeDriver();
dr1.get("http://google.com");
dr2.get("http://northeastraveller.com");
dr3.get("http://quora.com");
dr4.get("http://facebook.com");
// TODO Auto-generated method stub
}
}
I separated the Chrome part into a separate program named "Chrome_test", whose code is as follows
package test.selenium;
import org.openqa.selenium.chrome.ChromeDriver;
public class Chrome_Test{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C://chromedriver.exe");
ChromeDriver dr3=new ChromeDriver();
ChromeDriver dr4=new ChromeDriver();
dr3.get("http://quora.com");
dr4.get("http://facebook.com");
// TODO Auto-generated method stub
}
}
Now I'm getting the following error :
Error: Could not find or load main class test.selenium.Chrome_Test
I checked the classpath variables and all seems to be at place. What am I missing here?
You better place two backward slashes like:
System.setProperty("webdriver.chrome.driver", "C:\\ChromeDriver\\chromedriver.exe");
It will work.
I wrote code which downloads and installs the latest ChromeDriver automatically to the project root directory if none has been found. That way you can receive a ChromeDriver instance without actually worrying about the chromedriver.exe file. Feel free to adjust it to your needs. You still need to include Selenium libraries in your project though. For my ChromeDriverFactory class below you also need Apache Commons IO and Zip4J.
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class ChromeDriverFactory
{
private static String chromeDriverRepository = "http://chromedriver.storage.googleapis.com/";
public static WebDriver getChromeDriver() throws MalformedURLException,
IOException, ZipException
{
String chromeDriverFileName = "chromedriver.exe";
File chromeDriverFile = new File(chromeDriverFileName);
if (!chromeDriverFile.exists())
{
installChromeDriver();
}
setChromeDriverProperty(chromeDriverFileName);
return new ChromeDriver();
}
private static void setChromeDriverProperty(String chromeDriverFileName)
{
System.setProperty("webdriver.chrome.driver", chromeDriverFileName);
}
private static void installChromeDriver() throws IOException,
MalformedURLException, ZipException
{
String newestVersion = getNewestVersion();
String targetFile = "chromedriver_win32.zip";
String downloadUrl = chromeDriverRepository + newestVersion + "/"
+ targetFile;
String downloadFileName = FilenameUtils.getName(downloadUrl);
File downloadFile = new File(downloadFileName);
String projectRootDirectory = System.getProperty("user.dir");
FileUtils.copyURLToFile(new URL(downloadUrl), downloadFile);
ZipFile zipFile = new ZipFile(downloadFile);
zipFile.extractAll(projectRootDirectory);
FileUtils.deleteQuietly(downloadFile);
}
private static String getNewestVersion() throws MalformedURLException,
IOException
{
String newestVersionUrl = chromeDriverRepository + "LATEST_RELEASE";
InputStream input = new URL(newestVersionUrl).openStream();
return IOUtils.toString(input);
}
}
Change the chrome driver properties line with backslashes (\) and it would work.
System.setProperty("webdriver.chrome.driver", "C:\\ChromeDriver\\chromedriver.exe");

Created a java test script in eclipse, how do i run it in a headless linux CentOS VM?

The question above covers what I need I have created successful test scripts using eclipse on windows, but now i need to be able to run it in a linux vm through SSH and I have tried many things online and not had any success I know some changes may need to be done to the code also but I havnt managed to do that successfully either so please see the code below.
I have copied the src(test scripts) and libs(jars) files from the eclipse workspace to the linux vm and understood that to execute the selenium standalone server i use java -jar but that is about it. If you could walk me through the steps that need to be taken to run a test on firefox in the vm.
I have java and firefox installed.
Test Script
package test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class CorrectTestBackLink {
public BrowserList.DriverToUse used_driver = BrowserList.DriverToUse.IEXPLORER;
private BrowserSelector selectedDriver = new BrowserSelector(used_driver);
private WebDriver driver = selectedDriver.getDriver();
private StringBuffer verificationErrors = new StringBuffer();
private String baseUrl;
private static String resulterValue = "110";
private String valuecheck1;
#Before
public void setUp() throws Exception {
baseUrl = "http://url/";
//Set the column number and datatype of column by using either StringColumnNumber"Letter" or IntColumnNumber"Letter.
// Add aditional columns to database class where necessary.
}
public void calcResultChecker(){
driver.findElement(By.id("resulter")).getAttribute("value");
String valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
if (valuecheck1.equals(resulterValue)){
System.out.println("The Resulting value ("+valuecheck1+") is CORRRECT!");
}else{
System.err.println("The Resulting value is ("+valuecheck1+") is INCORRRECT!");
}
}
#Test
public void test2() throws Exception {
//calc page
driver.get(baseUrl + "calc.php");
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Entering 10 into 'firstnumber' field!");
driver.findElement(By.name("firstnumber")).sendKeys("10");
Thread.sleep(200);
driver.findElement(By.name("secondnumber")).sendKeys("11");
System.out.println("Entering 11 into 'secondnumber' field!");
Thread.sleep(200);
System.out.println("Clicking calculate button!");
driver.findElement(By.name("Calculate")).click();
Thread.sleep(200);
//calc results page
assertEquals(baseUrl + "calcresult.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
valuecheck1 = driver.findElement(By.id("resulter")).getAttribute("value");
assertEquals(valuecheck1, resulterValue);
Thread.sleep(200);
System.out.println("Clicking back Link!");
driver.findElement(By.linkText("Back")).click();
Thread.sleep(200);
//calc page check
assertEquals(baseUrl + "calc.php", driver.getCurrentUrl());
System.out.println("We are on the correct page ("+driver.getCurrentUrl()+").");
Thread.sleep(200);
System.out.println("Test Complete");
Thread.sleep(200);
driver.quit();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
}
Browser Selector
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class BrowserSelector {
private WebDriver driver;
public BrowserSelector(BrowserList.DriverToUse used_driver){
switch (used_driver){
case CHROME:{
System.setProperty("webdriver.chrome.driver", "C:/path/chromedriver.exe");
driver = new ChromeDriver();
break;
}
case FIREFOX:{
driver = new FirefoxDriver();
break;
}
case IEXPLORER:{
System.setProperty("webdriver.ie.driver","C:/path/IEDriverServer.exe");
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
driver = new InternetExplorerDriver(capabilities);
break;
}
}
}
public WebDriver getDriver(){
return driver;
}
}
People usually use either PhantomJS or "Headless Chrome" to run in a headless environment. Also, some people run regular browsers from a XVFB framebuffer. Here is a blog article that I found that explains how to install XVFB.
xvfb-run --server-args='-screen 0, 1024x768x16' google-chrome
-start-maximized http://example.com > /dev/null &
Using XVFB and VNC, you could probably login remotely and watch your tests run on the headless box but I haven't tried this. You would have to experiment with it.

Categories

Resources