CasperJS getting innerHTML of element by class

老子叫甜甜 提交于 2019-12-21 17:48:49

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!