PhantomJS Selenium Webdriver Java - setup and Error trying to find element with xpath



If you have a Selenium Webdriver framework that is working at its best!
All you now need is  a headless browser like PhantomJS to test your web applications that make the functional tests faster. (According to their website PhantomJS is “a headless WebKit with JavaScript API.” Webkit is the layout engine used by a few browsers, such as Chrome and Safari. So PhantomJS is a browser, but a headless one.)

Here are simple steps to add this capability in your selenium scripts:


  1. Download PhantomJS and extract the package. or windows its an exe file and for Mac its just a zip package you will need to extract. 
  2. Extract the phantomjs-1.9.x-windows.zip folder and locate phantomjs.exe file. 
  3. Copy this file to a common location where the framework libs are stored.(In my case I used the same space as ChromeDriver and IEDriver) 
  4. Add the following imports to your code:
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.phantomjs.PhantomJSDriver; import org.openqa.selenium.phantomjs.PhantomJSDriverService;


  1. In the place where you initialize WebDriver driver = new FirefoxDriver

  caps.setJavascriptEnabled(true); caps.setCapability(“takesScreenshot”, true);        caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,”C:\\Users\\\\Desktop\\Automation\\JavaLib\\PhantomJS\\phantomjs-1.9.2-windows\\phantomjs.exe”);   WebDriver driver = new PhantomJSDriver(caps);

  1. Continue coding as before with screenshots :) 
  driver.navigate().to("http://www.xyz.com");
  driver.manage().window().setSize( new Dimension( 1124, 850 ) );
  File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);     FileUtils.copyFile(scrFile, new File(“C:\\<savePath>\\iamnotadumbass+”.png”));

Note:  An issue I faced and was confused before I realized that this error message "Error trying to find element with xpath" does not really mean that but instead you need to be using http and not a https protocol for your webpage.

Alternative solution: 
The problem is most likely due to SSL certificate errors. If you start phantomjs with the --ignore-ssl-errors=yes option
phantomjs --ignore-ssl-errors=yes [phantomOptions] script.js [scriptOptions]
If that does not work try:
1. change user-agent
2. ssl-protocol that worked was tlsv1 or --ssl-protocol=any

Happy headless testing!

Popular posts from this blog

Software Testing @ Microsoft

Trim / Remove spaces in Xpath?