2015-11-01 51 views

回答

5

首先你需要检索所有你感兴趣的元素的表示这可以通过casper.getElementsInfo(selector)做到:

var elements = casper.getElementsInfo("p[data-whatever]"); 

这会给你的页面上的所有<p>元素有data-whatever属性集。如果您想按照data-whatever属性的值过滤该值,则需要根据您的需要使用attribute selectors

getElementsInfo()函数包含非常有用的信息,但不包含您要使用的实际元素。它只包含一个表示形式作为数组。

您可以迭代这些元素表示并在其上运行您的操作。你说你想“比较此属性与内部HTML”。这可以通过这种方式来完成:

elements.forEach(function(element){ 
    if (element.attributes["data-whatever"] === element.html) { 
     casper.echo("data attribute and content are exactly equal"); 
    } else { 
     casper.echo("data attribute and content are different"); 
    } 
}); 

请记住,你可以直接用正常的DOM功能的元件做到这一点,但你必须要做到这一点的casper.evaluate()里面,因为PhantomJS(其中CasperJS是建立在)有两个上下文和页面上下文是沙箱。另外,您不能从page context返回DOM节点。

相关问题