I want to get attribute of only string in <em>
tags of HTML page
I want to get "(868)"
1.
casper.then(function() {
var word = require('utils').dump(this.getElementAttribute(x('//*[@id="content"]/div[2]/h4/em'), 'em'));
console.log(word)
});
2.
casper.then(function() {
var word = require('utils').dump(this.getElementAttribute(h4[class="head"], 'em'));
console.log(word)
});
I tried both but it returns "null" How to solve the problem?
Take a look at documentation FAQ Can I access & manipulate DOM elements directly from the CasperJS environment?.
In the both of examples that you added in your question you tried to get the em
element as an attribute of h4
and that wrong because em
is a child and not attribute of h4
tag, so to select textContent
of an element you can try to use querySelector
with evaluate
function like following :
casper.then(function() {
var text = this.evaluate(function(){
return document.querySelector("h4.head em").textContent;
});
var word = require('utils').dump(text);
console.log(word);
}
Hope this helps.
<em>
is not an element attribute. It's an element itself. casper.getElementAttribute(selector, attribute)
will correctly retrieve the attribute text of an element, but your want to get the element text.
You can use casper.fetchText(selector)
for that. Note that fetchText()
will concatenate the contents of all matched elements into one string. If you don't want that, you either need to make sure that the selector only matches a single element or use other functions such as casper.getElementInfo(selector).text
.
Your second snippet cannot work, because you forgot "
around the selector and because of the above reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With