Search code examples
phantomjscasperjs

open the url, when .click() is performed using casperjs


i use the url "x" and find the next page button and perform .click() even on it. The .click() event is working fine and i found no errors with it. How can i make casperjs to redirect to the next page when .click() is performed. I thought of using casper.open() but couldn't find a way to use it combined with .click()

var casper = require('casper').create();
casper.start('url');

casper.then(function() {                                 
    if (this.exists('a.j-pagination-next')) {  //selector for the next page button

        this.click('a.j-pagination-next');   // Click on next page  button
         //should return the next page url 
        // this.open()
    }
    else{
        console.log("No such selector")  //end of pages or wrong selector 
    }
});
casper.run();

Solution

  • After you click the link, CasperJS will open the next page, no need to an extra open() call. You need to use then() or a waitFor*() function to perform the next step on the next page.

    var casper = require('casper').create();
    casper.start('url');
    
    casper.then(function() {                                 
        if (this.exists('a.j-pagination-next')) {  //selector for the next page button
    
            this.click('a.j-pagination-next');   // Click on next page  button
        }
        else{
            console.log("No such selector")  //end of pages or wrong selector 
        }
    });
    
    casper.then(fucntion(){
       console.log("I'm on the next page now");
    });
    
    casper.run();
    

    EDIT

    In order to get the current URL you should call this.getCurrentUrl():

    var casper = require('casper').create();
    casper.start('url');
    
    casper.then(function() {                                 
        if (this.exists('a.j-pagination-next')) {  //selector for the next page button
    
            this.click('a.j-pagination-next');   // Click on next page  button
        }
        else{
            console.log("No such selector")  //end of pages or wrong selector 
        }
    });
    
    casper.then(fucntion(){
       console.log(this.getCurrentUrl());
    });
    
    casper.run();
    

    Take a look at How to get get URL of new page using casperJS