Casperjs点击方法

时间:2013-04-02 06:32:10

标签: javascript web-scraping casperjs

我对casperjs和javascript很新,但我在其他领域拥有相当丰富的编码经验。目前我正在尝试运行的代码只是访问一个网站并点击链接,这应该是直截了当的,但我遇到了麻烦。

var casper = require('casper').create();
var x = require('casper').selectXPath;

casper.start('http://www.guru.com/emp/search.aspx?keyword=#&&page=1&sort=Earnings');

casper.then(function() {
    this.test.assertExists({
        type: 'xpath',
        path: '//*[@class="paddingLeft5 txt11px txt666"]/a[text()="Next"]'
    }, "Got Here");
});

casper.then(function() {
    var firstUrl = this.getCurrentUrl()
});

casper.thenClick(x('//*[@class="paddingLeft5 txt11px txt666"]/a[text()="Next"]'), function() {
    console.log("Woop!");
});

casper.waitFor(function check() {
    return this.evaluate(function() {
        return this.getCurrentUrl() != firstUrl;
    });
}, function then() {
    console.log(this.getCurrentUrl());
});


casper.run();

目前这个时间超过5000毫秒而没有包装在waitFor中它只是打印两次相同的URL。

2 个答案:

答案 0 :(得分:8)

这应该是你要找的。 请注意,我将firstUrl移动为全局变量;这样,Casper.waitFor()就可以访问它了。

此外,在this.evaluate()内使用Casper.waitFor()是不必要的,并且实际上禁止接收错误消息,因为远程页面上既不存在this也不存在firstUrl。这是因为您希望在Casper.evaluate()内访问的任何变量必须在函数之后作为参数传递。

var casper = require('casper').create();
var x = require('casper').selectXPath;
var firstUrl;
casper.start('http://www.guru.com/emp/search.aspx?keyword=#&&page=1&sort=Earnings');

casper.then(function() {
    this.test.assertExists({
        type: 'xpath',
        path: '//*[@class="paddingLeft5 txt11px txt666"]/a[text()="Next"]'
    }, "Got Here");
});

casper.then(function() {
    firstUrl = this.getCurrentUrl()
});

casper.thenClick(x('//*[@class="paddingLeft5 txt11px txt666"]/a[text()="Next"]'), function() {
    console.log("Woop!");
});

casper.waitFor(function check() {
    return this.getCurrentUrl() != firstUrl;
}, function then() {
    console.log(this.getCurrentUrl());
});


casper.run();

这是我在运行上述代码时得到的结果:

Woop!
http://www.guru.com/emp/search.aspx?keyword=#&&sort=Earnings&page=2

答案 1 :(得分:0)

看起来网站严重依赖JavaScript进行导航...

在处理下一步之前,您应该尝试更改waitFor网址。