问题
I'm new to CasperJS and I'm having a few issues getting the innerHTML out of <p class="city">Data I Need</p>
I have tried a few things, but nothing seems to get it.
var city_name= casper.evaluate(".//*[@class='city_name']", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
var friend_username = city_name.innerHTML;
and
var city_name = this.evaluate(function() {
return document.querySelector(".//*[@class='city_name']").innerHtml;
});
回答1:
CasperJS works by default with CSS selectors:
var city_name = casper.evaluate(function() {
return document.querySelector(".city_name").innerHTML;
});
Note that the property is innerHTML not innerHtml. Also note that casper.evaluate() is the interface to the page context and has nothing to do with document.evaluate().
You can of course use XPath expressions with a CasperJS utility. Functions like casper.getElementInfo() provide you with some additional properties like html which is actually the innerHTML property on the corresponding DOM element.
var x = require("casper").selectXPath;
...
var city_name = casper.getElementInfo(x(".//*[@class='city_name']")).html;
回答2:
For me, I liked using casper's getElementInfo() method:
casper.getElementInfo('<insert CSS selector>').html
Or in my case, I wanted the inner text:
casper.getElementInfo('<insert CSS selector>').text
来源:https://stackoverflow.com/questions/30486233/casperjs-getting-innerhtml-of-element-by-class