Monday, 18 March 2013

Headless Browser Testing using PhantomJS - GhostDriver | WebDriver


PhantomJS is a Headless Webkit with JavaScript API. It has fast & native support for various Web Standards: DOM handling, CSS selector, JSON, canvas and SVG.  GhostDriver is a Webdriver wire protocol in simple JS for PhantomJS.  PhantomJS is used for Headless Testing of Web Applications that comes with in-built GhostDriver.

Involves,
1| General command-line based testing.
2| As a part of a Continuous Integration System.

PhantomJS is not a Test framework, it is used only to LAUNCH the tests via a suitable Test Runner.

Framework used: WebDriver
Test Runner: GhostDriver

CI systems: Make sure PhantomJS is installed properly on the slave/build agent and it is ready to go. Headless Browser is a Web Browser without a GUI (Graphical User Interface). It access Web Pages but doesn't show them to any human being. Headless Browser should be able to parse JavaScript.



Configure PhantomJS

1. Download phantomjs.exe
2. Extract the phantomjs-1.8.x-windows.zip folder and locate phantomjs.exe file to C:/ folder
3. Add the following imports to your code:

import org.openqa.selenium.phantomjs.PhantomJSDriver;
import org.openqa.selenium.phantomjs.PhantomJSDriverService;
import org.openqa.selenium.remote.DesiredCapabilities;

4. Replace the object, "driver" specifying "FirefoxDriver" with "PhantomJSDriver".

Replace the code,
WebDriver driver = new FirefoxDriver

with
DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true); // not really needed: JS enabled by default
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C:/phantomjs.exe");
WebDriver driver = new PhantomJSDriver(caps);

5. Run Test.

Note|
PhantomJSDriver-1.0.x.jar can also be downloaded and configured in Eclipse manually.



PhantomJS | Screen Capture

DesiredCapabilities caps = new DesiredCapabilities();
caps.setJavascriptEnabled(true); // not really needed: JS enabled by default
caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, "C://phantomjs.exe");
caps.setCapability("takesScreenshot", true);
driver = new PhantomJSDriver(caps);  
baseUrl = "http://www.xyz.com";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void test01() throws Exception {
driver.get(baseUrl + "/");   
long iStart = System.currentTimeMillis(); // start timing
<your script>
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\sample.jpeg"),true);    
System.out.println("Single Page Time:" + (System.currentTimeMillis() - iStart)); // end timing    
}

76 comments:

  1. Hey Prashanth,

    I've been looking for this solution everywhere. Thank you so much. Since it's designed to hide all of the actions from the user, is there anyway to make sure this works besides using print statements in the code? Again, thank you.

    ReplyDelete
    Replies
    1. I guess PhantomJS supports screenshots as well.

      Delete
    2. Hi Max,

      Phantomjs supports Screen capture as well. Please find the example I have given above.

      Cheers
      _
      Prashanth Sams

      Delete
  2. Thanks a lot for great tutorial. Highly appreciated.

    ReplyDelete
  3. Can you give me a real time example where we use this in Automation? Like some example application

    ReplyDelete
  4. Thanks a lot .... best tut about phantom on the net ..

    ReplyDelete
  5. Nice article, prashanth!!
    Althought I'm new to selenium and phantoms.. i'm trying something with nodejs , but not getting what i expect..

    can you please help me on this..

    http://stackoverflow.com/q/24556738/2958224

    Much appreciated..!!

    ReplyDelete
  6. Hi Prashanth,

    This is very nice and helpful article.

    Now, can you please tell me, how can i enable cookie using selenium and phantoms?

    ReplyDelete
  7. here's how i do cookies in my GebConfig.groovy....

    DesiredCapabilities dCaps = new DesiredCapabilities()
    dCaps.setJavascriptEnabled(true);
    dCaps.setCapability("takesScreenshot", false);
    dCaps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY,
    '/Users/en032339/Desktop/phantomjs-1.9.7-windows/phantomjs.exe')
    dCaps.setCapability(PhantomJSDriverService.PHANTOMJS_CLI_ARGS,
    ['--cookies-file=phantomjs_cookies.txt', '--load-images=no'] as String[])
    WebDriver driver = new PhantomJSDriver(dCaps)

    ReplyDelete
  8. HI can you please tell me how to handle download s in headless testing.
    eg: we have a link to download excel file .In selenium we are using autoit script to handle the download windows but here i have no guess can anyone please help me on this

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. How to use PhantomJS with maven?

    ReplyDelete
  11. thank you so much..
    very useful documnet..
    so many thanks

    ReplyDelete
  12. very good Article. Is there such kind of write-up for PhantomJS, Selenium on Linux OS?

    ReplyDelete
  13. can we use phantomjs in grid, please help me with that

    ReplyDelete
  14. Hello,

    I found this site just now. Your code has been a good help for me but there are two things:

    1. FileUtils.copyFile doesn't work for me. I saw this on several sites but I have to use FileCopyUtils.copyFile() otherwise I get an compilation error that this method does not exist.

    2. Open a site and make a screenshot isn't enough for me. For a test I have to click buttons, insert values in text fields,..
    But whatever I do I always get a NoSuchElementException. I tried

    - driver.findElementBy.id/xpath/tagName/cssSelector
    - actions.moveToElement(driver.findElementBy.id/xpath/tagName/cssSelector)
    - both with 30 seconds timeout

    I'm sick of it. Maybe you have an idea how to find a webelement with PhantomJSDriver?

    Thanks and a nice day
    Achim

    ReplyDelete
  15. I really enjoy the blog.Much thanks again. Really Great selenium Online course Bangalore

    ReplyDelete
  16. It would have been the happiest moment for you,I mean if we have been waiting for something to happen and when it happens we forgot all hardwork and wait for getting that happened.
    It would have been the happiest moment for you,I mean if we have been waiting for something to happen and when it happens we forgot all hardwork and wait for getting that happened.

    ReplyDelete
  17. Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.python training in bangalore

    ReplyDelete
  18. Its really helpful for the users of this site. I am also searching about these type of sites now a days. So your site really helps me for searching the new and great stuff.vmware training in bangalore

    ReplyDelete
  19. These provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post.salesforce developer training in bangalore

    ReplyDelete
  20. Linking is very useful thing.you have really helped lots of people who visit blog and provide them use full information.devops training in bangalore

    ReplyDelete
  21. I know that it takes a lot of effort and hard work to write such an informative content like this.cloud computing training in bangalore

    ReplyDelete
  22. Such a great word which you use in your article and article is amazing knowledge. thank you for sharing it.

    Looking for Training Institute in Bangalore , India. Softgen Infotech is the best one to offers 85+ computer training courses including IT software course in Bangalore, India. Also it provides placement assistance service in Bangalore for IT.
    Best Software Training Institute in Bangalore

    ReplyDelete
  23. Really i appreciate the effort you made to share the knowledge. The topic here i found was really effective...

    Best Training Institute in Bangalore BTM. My Class Training Bangalore training center for certified course, learning on Software Training Course by expert faculties, also provides job placement for fresher, experience job seekers.
    Training Institute in Bangalore

    ReplyDelete
  24. Post is very useful. Thank you, this useful information.

    Start your journey with Training Institute in Bangaloreand get hands-on Experience with 100% Placement assistance from Expert Trainers with 8+ Years of experience @eTechno Soft Solutions Located in BTM Layout Bangalore.
    SAP Training in Bangalore

    ReplyDelete
  25. Thanks for one marvelous posting! I enjoyed reading it; you are a great author. I will make sure to bookmark your blog and may come back someday. I want to encourage that you continue your great posts.

    ReplyDelete
  26. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Data Science Training in Electronic City

    ReplyDelete
  27. Thanks you for sharing this informative and useful article.Really interesting and awesome article.
    Data Science Training in Hyderabad

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. thanks for sharing nice information.....
    more : https://www.kellytechno.com/Hyderabad/Course/AI-Training-In-Hyderabad

    ReplyDelete
  30. Such an excellent and interesting blog, do post like this more with more information, this was very useful. Salesforce Training Canada   

    ReplyDelete
  31. Hey, i liked reading your article. You may go through few of my creative works here
    Jobs.fsoma
    Lucillerickman

    ReplyDelete
  32. This comment has been removed by the author.

    ReplyDelete
  33. I like your post. Everyone should do read this blog. Because this blog is important for all now I will share this post. Thank you so much for share with us.

    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training


    ReplyDelete
  34. Really great post, Thank you for sharing This knowledge.Excellently written article, if only all bloggers offered the same level of content as you, the internet would be a much better place. Please keep it up!
    java training in chennai

    java training in omr

    aws training in chennai

    aws training in omr

    python training in chennai

    python training in omr

    selenium training in chennai

    selenium training in omr

    ReplyDelete
  35. Nice blog with new information,
    Thanks to share with us,

    http://www.loveshelbey.com/2018/03/my-new-website.html?showComment=1596300388321#c8042707041662775466

    ReplyDelete
  36. Attend online training from one of the best training institute Data Science

    Course in Hyderabad

    ReplyDelete
  37. Great blog!!! It is very impressive... thanks for sharing with us...keep posting.

    Python Training in Hyderabad

    Best PythonTraining Institutes in Hyderabad

    ReplyDelete
  38. Good Post! Thank you so much for sharing this pretty post, it was so good to read keep blogging.

    Artificial Intelligence Training in Hyderabad

    ReplyDelete
  39. Just saying thanks will not just be sufficient, for the fantasti c lucidity in your writing. I will instantly grab your rss feed to stay informed of any updates.<a href="https://www.excelr.com/business-analytics-training-in-pune/”> Business Analytics Courses</a>
    I really enjoy reading and also appreciate your work.
    Three are usually cheap Ralph Lauren available for sale each and every time you wish to buy.

    ReplyDelete
  40. That is a good tip particularly to those fresh to the biosphere. Short but very accurate info… Many thanks for sharing this one. A must read post!

    AWS Training in Hyderabad

    ReplyDelete
  41. Your work is very good, and I appreciate you and hopping for some more informative posts
    <a href="https://www.excelr.com/business-analytics-training-in-pune/”> Courses in Business Analytics</a>
    It is perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I could I desire to suggest you few interesting things or tips. Perhaps you could write next articles referring to this article. I want to read more things about it!

    ReplyDelete
  42. your blog' s design is simple and clean and i like it. Your blog posts about Online writing Help are superb. Please keep them coming. Greets!

    data science course near me
    data science online training

    ReplyDelete
  43. If you're looking for a more expensive option, then you should consider the hello baby monitor. It is the first monitor to use voice recognition technology, which means that instead of having to press buttons for your child to speak, the monitor can read their voice and record that. Then you simply put a microphone on your baby and use that to listen in as you speak to your child.

    ReplyDelete
  44. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up

    Devops Training in Hyderabad

    Hadoop Training in Hyderabad

    Python Training in Hyderabad

    ReplyDelete
  45. Hi! This is my first visit to your blog! We are a team of volunteers and new initiatives in the same niche. Blog gave us useful information to work. You have done an amazing job!
    data science certification

    ReplyDelete
  46. It is imperative that we read blog post very carefully. I am already done it and find that this post is really amazing. ExcelR Business Analytics Courses

    ReplyDelete
  47. I think this is a standout amongst the most critical data for me. What"s more, i"m happy perusing your article. Be that as it may, ought to comment on some broad things ExcelR Business Analytics Courses

    ReplyDelete
  48. Thanks for the Valuable information.Really useful information. Thank you so much for sharing. It will help everyone.

    Tableau Training in Delhi.


    FOR MORE INFO:

    ReplyDelete
  49. I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end.
    Python Training In Pune

    ReplyDelete
  50. Chemistry is our forte. We provide chemicals ranging from fine chemcials for early R&D application to large scale industrial production. Glycidol (556-52-5 ) manufacturer USA is a leading developer, manufacturer and exporter of API, intermediates of API, Fragrance intermediates, Specialty Chemicals & other Customized Products.
    Located in Asia's largest chemical industrial estate, Rampur, U.P., Agex Pharma begins its operations as a small scale unit in 1990 and in a span of three decades in market has emerged as a leading player
    which believes in quality. Today with an inventory of 500+ products, 200+ clients globally Agex Pharma has placed itself in one of the most sought after companies in the nation for Fine and Rare Specialty
    chemicals.Our business is based on a simple philosophy: to provide our customers with high quality fine chemicals at reasonable prices and with fast turn-around schedules.

    ReplyDelete
  51. Ворожение позволяет предположить, что вас ждет в предстоящее время. Гадание, что он чувствует ко мне? - способ увидеть приближающиеся события постоянно привлекал человека. Всякий мечтает предугадать свою судьбу и представляет определенные типы гадания наиболее достоверными.

    ReplyDelete
  52. wordpress website design studio Need professional WordPress Web Design Services? We're experts in developing attractive mobile-friendly WordPress websites for businesses. Contact us today!

    ReplyDelete
  53. Wishing you a Thursday with an abundance of God's blessings for you and your loved ones. I pray for this Thursday to bring an amazing sense of . Thursday Quotes For The Day

    ReplyDelete