Casperjs is an open source browser navigation scripting and testing tool written in JavaScript for PhantomJS. Casperjs can be installed on windows, mac os x and linux. We can install phantomjs and casperjs using npm by running following commands:-
For Installing Casperjs:-
npm install casperjs -g
For Installing Phantomjs:-
npm -g install phantomjs-prebuilt
Now first of all before writing script for Login to a WordPress site we would first create a directory where we put our test.js file and use npm init command to create package.json file in directory.
mkdir casperdemo cd casperdemo npm init
Now we will create a test.js in casperdemo directory for Login to a WordPress site and taking screenshot of it. Following script will be written in test.js file:-
var page = require('webpage').create(); var casper = require('casper').create(); var urlBeforeLoggedIn = "http://garima.com/auction/wp-login.php"; var urlAfterLoggedIn = "http://garima.com/auction/wp-admin"; casper.start(urlBeforeLoggedIn); casper.waitForSelector('form[method="post"]', function() { casper.fillSelectors('form[method="post"]', { 'input[name="log"]': 'admin', 'input[name="pwd"]': 'admin' }, true); }); casper.waitForUrl(urlAfterLoggedIn, function() { this.viewport(3000, 1080); this.capture('./screenshot.png', {top: 0,left: 0,width: 3000, height: 1080}); }); casper.run();
Here, first of all we have two variables urlBeforeLoggedIn and urlAfterLoggedIn in which we put the url which is used before login into a WordPress site and url after logged into the website respectively.
var urlBeforeLoggedIn = "http://garima.com/auction/wp-login.php"; var urlAfterLoggedIn = "http://garima.com/auction/wp-admin";
For opening the website we use casper.start (urlBeforeLoggedIn) and for submitting a post form we have used following script:-
casper.waitForSelector('form[method="post"]', function() { casper.fillSelectors('form[method="post"]', { 'input[name="log"]': 'admin', 'input[name="pwd"]': 'admin' }, true); });
For taking screenshot of logged in window in WordPress we are using following script:-
casper.waitForUrl(urlAfterLoggedIn, function() { this.viewport(3000, 1080); this.capture('./screenshot.png', {top: 0,left: 0,width: 3000, height: 1080}); });
Now we will run the test.js file in terminal by using the following command:-
casperjs test.js
After running this command we will get a screenshot of successful Login to a WordPress site which will be saved in casperdemo directory like below image:-
Screenshot.png will look like below image:-
That’s all about Login to a WordPress site using Casperjs.
Thanks for reading this blog !!
3 comments