Reputation: 4297
I have a webpage with this between lines:
<a href="http://foo.com/home.do?SID=3443132">...
I need to extract "href" attribute using XPath. In the API of CasperJS is wrote this information about this: clientutils.getElementByXPath.
Here is my code:
phantom.casperPath = '..n1k0-casperjs-5428865';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');
var casper = require('casper').create();
var url = "...";
casper.start(url, function() {
casper.echo("started");
});
var x = require('casper').selectXPath;
casper.then(function()
{
casper.echo("getsid");
this.test.assertExists(x('//a[contains(@href, "home.do?SID=")]'), 'the element exists');
var element = __utils__.getElementByXPath('//a[contains(@href, "home.do?SID=")]');
});
But it fails. it returns this:
false
undefined
started
getsid
PASS the element exists <== XPATH WORKS
FAIL ReferenceError: Can't find variable: __utils__
# type: uncaughtError
# error: "ReferenceError: Can't find variable: __utils__"
ReferenceError: Can't find variable: __utils__
Upvotes: 4
Views: 11682
Reputation: 61892
As pointed out in the comments, you would have to use __utils__
inside the evaluate
callback, because it is injected into the page. Since you want(ed) the href
, you could use:
casper.then(function(){
casper.echo("getsid");
this.test.assertExists(x('//a[contains(@href, "home.do?SID=")]'), 'the element exists');
var href = this.evaluate(function(){
var element = __utils__.getElementByXPath('//a[contains(@href, "home.do?SID=")]');
return element.href;
});
});
This can be shortened with the usage of casper.getElementAttribute
:
casper.then(function(){
casper.echo("getsid");
this.test.assertExists(x('//a[contains(@href, "home.do?SID=")]'), 'the element exists');
var href = this.getElementAttribute(x('//a[contains(@href, "home.do?SID=")]'), "href");
});
You can also use casper.getElementInfo
to get the complete info of the element including all the attributes (but only some properties).
Upvotes: 3
Reputation: 1711
Try this:
phantom.casperPath = '..n1k0-casperjs-5428865';
phantom.injectJs(phantom.casperPath + '\\bin\\bootstrap.js');
var url = "...";
var casper = require('casper').create();
var x = require('casper').selectXPath;
casper.start(url, function() {
casper.echo("started");
});
casper.then(function() {
casper.echo("getsid");
var xpath = '//a[contains(@href, "home.do?SID=")]';
var xpath_arr = { type: 'xpath', path: xpath};
this.test.assertExists(xpath_arr, 'the element exists');
var element = x(xpath);
});
Upvotes: 3