Unable to start Chrome Driver in Selenium Webdriver 2 - java

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");

Related

in selenium webdriver while writing code for to take screeshot getting this error

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method copyFile(java.io.File, java.io.File) in the type FileUtils is not applicable for the arguments (java.io.File, com.gargoylesoftware.htmlunit.javascript.host.file.File)
The constructor File(String) is not visible
at DEMO.Screenshot.Homepage(Screenshot.java:37)
at DEMO.Screenshot.main(Screenshot.java:47)
Sample Code:
package DEMO;
import java.io.IOException;
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Platform;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
public class Screenshot {
WebDriver driver;
public void Homepage() {
System.setProperty("webdriver.gecko.driver", "E:\\selenium_course\\geckodriver.exe");
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.firefox();
capabilities.setBrowserName("firefox");
capabilities.setVersion("your firefox version");
capabilities.setPlatform(Platform.WINDOWS);
capabilities.setCapability("marionette", false);
driver = new FirefoxDriver(capabilities);
// driver=new ChromeDriver();
driver.get("https://amazon.com");
driver.manage().window().maximize();
// take screen shot and store into variable
java.io.File src = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// copy screen shot into local system
try {
FileUtils.copyFile(src, new File("E:\\selenium_course\\Screen\\homepage.png"));
} catch (IOException t) {
System.out.println(t.getMessage());
}
driver.close();
}
public static void main(String[] args) {
Screenshot s = new Screenshot();
s.Homepage();
}
}
You use File from com.gargoylesoftware.htmlunit.javascript.host.file, you should use File from java.io. Replace the import
import com.gargoylesoftware.htmlunit.javascript.host.file.File;
With
import java.io.File;
//instead of using try catch at
FILEUTIL.cpy file use that exception handler at public static void main//
public static void main(String[] args) throws exception

Selenium WebDriver throwing TimoutException while invoking getScreenshotAs()

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.

Why I can't take a screenshot using selenium webdriver in java?

I am working on a project on regression testing using Selenium webdriver in java. I have written the following code to take a screenshot.
package SelTest;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class takeScreenShottest {
public WebDriver driver;
#Test
public void openBrowser() throws Exception{
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://www.google.com");
try{
driver.findElement(By.id("testing")).sendKeys("test");
}catch(Exception e){
System.out.print("I am in Exception");
getscreenshot();
}
}
public void getscreenshot() throws Exception{
File scrFile=((TakesScreenshot)).driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("E:\\Android-workspace\\Test1\\src\\ScreenShot\\screenshot.png"));
}
public static void main(String[] args) throws Exception{
takeScreenShottest ts = new takeScreenShottest();
ts.openBrowser();
}
}
I am getting an error for
File scrFile=((TakesScreenshot)).driver).getScreenshotAs(OutputType.FILE);
Why is this happening?
You can use this as below:
FileUtils.copyFile(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE), new File("E:\\Android-workspace\\Test1\\src\\ScreenShot\\screenshot.png"));
Error solved. The error was TakesScreenshot cannot be resolved to a variable and Syntax error on token ")". So, I removed the ")." So the correct syntax was
File srcFile=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

log in in all browsers with selenium

There is problem I cant resolve for 2 days. I need to login in many browsers in many machines on same sites. Its time-consuming task so I decide to do it with Selenium. I think problem is that while running test selenium does not save cookies. I find that its real to save cookies in file and then open them in next selenium tests but i need all browsers are logged in for manual testing. Here is my code
package automationFramework;
import java.io.File;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
public class FirstTestCase {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
File profileDirectory = new File(
"C:\\Users\\User\\AppData\\Roaming\\Mozilla\\Firefox\\Profiles\\n8a2y7sp.default");//path to firefox profile
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
driver = new FirefoxDriver(profile);
baseUrl = "http://facebook.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testVk() throws Exception {
driver.get(baseUrl);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(""); // login
driver.findElement(By.id("pass")).clear();
driver.findElement(By.id("pass")).sendKeys(""); //password
driver.findElement(By.id("loginbutton")).click();
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
What exactly do you mean? Do you try to achieve multiple browsers that access the same site simultaneously? If so, you will need to set up more than one driver instance.
If you'd like to achieve it sequentially, just use a loop where you open the driver and get the URL, do your thing, then kill the driver instance, repeat.

Unable to start Internet Explorer or Chrome in Selenium Webdriver (JAVA)

I am trying to start up an IE instance using Webdriver. I can't figure out why I'm receiving these errors, my code appears to be identical to every example I can find on the web.
I'm using Java and testng.
Here is the code:
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Tests {
File file = new File("C:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
}
The following errors are displaying, all of these errors are on the "System.setProperty" line.
Multiple markers at this line
- Syntax error on token ""webdriver.ie.driver"", invalid
FormalParameterList
- Syntax error on token(s), misplaced construct(s)
- Syntax error on tokens, FormalParameter expected instead
Please note that I have the exact same problem if I try to use Chrome with this code:
File file = new File("C:/selenium/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driver = new ChromeDriver();
You are running your code from inside class instead of running it from inside method. Covert it to something like
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Tests {
public static void main(String[] args) { // <-- you need a method!
File file = new File("C:\\selenium\\IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
WebDriver driver = new InternetExplorerDriver();
}
}
try this :
I'm using "mvn test" to lunch the test process so the path of the IE driver may be changed
File file = new File("classes/tools/IEDriverServer.exe");
Use IE driver with Capabilities
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
caps.setCapability("ignoreZoomSetting", true);
caps.setCapability("nativeEvents", false);
WebDriver driver = new InternetExplorerDriver(caps);
It may help you :)
Actually, on the updated eclipse version, you might have to use #suppressWarnings
package Login;
import java.io.File;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.WebDriver;
public class Login {
public static void main(String[] args) {
File file = new File("C:\\Users\\IEDRiverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath() );
#SuppressWarnings("unused")
WebDriver driver = new InternetExplorerDriver();
}
}
Simple example:
public class IE {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.ie.driver", "D:\\Sathish\\soft\\SELENIUM\\LatestDownloads\\selenium\\IEDriverServer.exe");
WebDriver driver = new InternetExplorerDriver();
driver.get("www.google.com");
driver.findElement(By.id("gbqfq")).sendKeys("abc");
driver.close();
}
}
Do the below process.
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
if (browserName.equalsIgnoreCase("InternetExplorer")) {
DesiredCapabilities caps = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", "drivers/IEDriverServer.exe");
caps.setCapability( InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true);
caps.setCapability("nativeEvents", false);
browser = new InternetExplorerDriver(caps);
Then after, In IE, from the Tools menu (or the gear icon in the toolbar in later versions), select "Internet options." Go to the Security tab. At the bottom of the dialog for each zone, you should see a check box labeled "Enable Protected Mode." Set the value of the check box to the same value,
either checked or unchecked, for each zone.
I have applied the same thing at my end, it works fine.

Categories

Resources