How to get get URL of new page using casperJS

让人想犯罪 __ 提交于 2019-12-11 00:20:11

问题


I am using casperJS to get links when clicking a button. The links are returned with window.open in javaScript.

The code I have written logs all the pages after clicking button, but phantom is not exiting in terminal window. Also some pages only show about:blank, especially the last ones.

var casper = require('casper').create();
var page = require('webpage').create();

var address = 'http://www.example.com';

page.open(address, function() {

    page.onPageCreated = function(newPage) {

        newPage.onClosing = function(closingPage) {
            console.log('A child page is closing: ' + closingPage.url);

            /* if i set phantom.exit() it will only log the first page url. 
            Problem: I need all page urls. */
        }

    }

    page.evaluate(function() {
        $(".button").click();
    });

}

回答1:


The method "getCurrentUrl()" will return the current url. Here is an easy (not really meaningful) example:

casper.test.begin('My Test', 1 , function suite(test) {

        casper.start().viewport(1600,1000).thenOpen("https://blabla.de", function() {
                var mylink = this.getElementInfo("#linkid").text;
                this.clickLabel(mylink);
        });

        casper.waitForSelector("#page2", function() {
                this.echo(this.getCurrentUrl());
        });

        casper.run(function() {
                test.done();
        });

});



回答2:


You can get the URL of the current page in CasperJS using one of the following methods:

  • casper.getCurrentUrl():
    • Retrieves the current page URL. Note that the URL will be URL-decoded.
  • casper.page.url:
    • Accesses the existing PhantomJS WebPage instance (page), and gets the current URL of the web page.
  • casper.evaluate(function () { return location.href; }):
    • Evaluates the page URL in the Page DOM Environment.


来源:https://stackoverflow.com/questions/33696904/how-to-get-get-url-of-new-page-using-casperjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!