如何从casperJS脚本中的按钮检索href元素?

时间:2014-01-04 18:10:44

标签: javascript casperjs

casper.then(function() {
this.test.assertExists({
    type: 'xpath',
    path: '//*[@id="wrapper"]/div[1]/a[2]'
}, "Found Multiviewer button");

});

找到上面的按钮,但我无法访问href元素:

var element = x('//*[@id="wrapper"]/div[1]/a[2]');

console.log('element'+this.getElementAttribute(element,'href'));

结果:

TypeError: 'undefined' is not a function (evaluating 'this.getElementAttribute(element,'href')')

我也尝试过:

this.getElementAttribute('//*[@id="wrapper"]/div[1]/a[2]','href')')

casperJS版本是1.1.0-beta3(OSX 10.8.5)

我检索到网址后,我需要打开它...

var baseTargetUrl;
casper.then(function() {
    var element = x('//*[@id="wrapper"]/div[1]/a[2]');
    console.log('url is: '+this.getElementAttribute(element,'href'));
    baseTargetUrl = this.getElementAttribute(element,'href');
});

casper.thenOpen(baseTargetUrl, function() {
    this.echo(this.getTitle());
});

错误:

FAIL TypeError: 'undefined' is not an object (evaluating 'url.toLowerCase')
#    type: uncaughtError
#    error: 'undefined' is not an object (evaluating 'url.toLowerCase')
#           TypeError: 'undefined' is not an object (evaluating 'url.toLowerCase')
#               at cleanUrl (/usr/local/lib/node_modules/casperjs/modules/utils.js:112)
#               at open (/usr/local/lib/node_modules/casperjs/modules/casper.js:1405)
#               at _step (/usr/local/lib/node_modules/casperjs/modules/casper.js:1832)
#               at runStep (/usr/local/lib/node_modules/casperjs/modules/casper.js:1553)
#               at checkStep (/usr/local/lib/node_modules/casperjs/modules/casper.js:399)
#    stack: not provided
TypeError: 'undefined' is not an object (evaluating 'url.toLowerCase')          
  /usr/local/lib/node_modules/casperjs/modules/utils.js:112 in cleanUrl
  /usr/local/lib/node_modules/casperjs/modules/casper.js:1405 in open
  /usr/local/lib/node_modules/casperjs/modules/casper.js:1832 in _step
  /usr/local/lib/node_modules/casperjs/modules/casper.js:1553 in runStep
  /usr/local/lib/node_modules/casperjs/modules/casper.js:399 in checkStep
FAIL TypeError: 'undefined' is not an object (evaluating 'url.toLowerCase')
#    type: error
#    subject: false
#    error: "TypeError: 'undefined' is not an object (evaluating 'url.toLowerCase')"
#    stack: in cleanUrl() in /usr/local/lib/node_modules/casperjs/modules/utils.js:112
in open() in /usr/local/lib/node_modules/casperjs/modules/casper.js:1405
in _step() in /usr/local/lib/node_modules/casperjs/modules/casper.js:1832
in runStep() in /usr/local/lib/node_modules/casperjs/modules/casper.js:1553
in checkStep() in /usr/local/lib/node_modules/casperjs/modules/casper.js:399

我应该如何将URL传递给下一个函数?

1 个答案:

答案 0 :(得分:1)

看起来问题是你试图用this引用casper,但是你没有把它包装在casper函数中。

casper.then(function() {
    var element = x('//*[@id="wrapper"]/div[1]/a[2]');
    console.log('element'+this.getElementAttribute(element,'href'));
});