Selenium
webdriver helps in automating web applications by loading the
application in browsers. But during the execution it's not possible
to minimize/hide the browser even if the user intend to. There are
tweaks such as setting the window size like
driver.manage().window().setPosition(new
Point(-2000, 0));. But
a question arises, if browser is invoked in minimized mode, whats the
need of invoking it. Why don't we run it in background? Such a
question arised in mind too. A good answer for this is PhantomJS.
PhantomJS is a headless WebKit scriptable with a JavaScript API. It
has fast
and native
support for various web standards: DOM handling, CSS selector, JSON,
Canvas, and SVG.
Like
many other packages, PhantomJS supports Selenium webdriver too. You
need to download the executable file from PhantomJS webpage, store
the .exe file in class resource path. This can be used to load
webdriver.
See
below code:
public void navigation() {
DesiredCapabilities caps = new DesiredCapabilities();
DesiredCapabilities caps = new DesiredCapabilities();
String
phantompath=
loadPhantomJS();
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
phantompath);
try{
driver
= new
PhantomJSDriver(caps);
}
catch(IllegalStateException
ie){
if(driver!=null){
driver.quit();
}
}
driver.manage().window().setSize(new Dimension(1124,1024));
driver.get(obj.getProperty("url"));
}
private static String loadPhantomJS() {
String phantomJs = "phantomjs.exe";
String dir1 = System.getProperty("user.dir");;
try {
InputStream in = Exitfunctions.class.getResourceAsStream("/phantom/" + phantomJs);
File fileOut = new File(dir1 +"/"+ phantomJs);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
return fileOut.getAbsolutePath();
} catch (Exception e) {
return "";
}
}
driver.get(obj.getProperty("url"));
}
private static String loadPhantomJS() {
String phantomJs = "phantomjs.exe";
String dir1 = System.getProperty("user.dir");;
try {
InputStream in = Exitfunctions.class.getResourceAsStream("/phantom/" + phantomJs);
File fileOut = new File(dir1 +"/"+ phantomJs);
OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();
return fileOut.getAbsolutePath();
} catch (Exception e) {
return "";
}
}
PhantomJS
need to quit once the execution is done or any exception occurs.
Unless, PhantomJS service will be running in background which may
cause exception while next execution of your program. You may use
driver.quit();
itself.
Link
to download PhantomJS: http://phantomjs.org/
0 comments:
Post a Comment