在 CasperJS 中获取具有特定(数据)属性的每个元素
Get every element with a specific (data-) attribute in CasperJS
我正在尝试使用 CasperJS 测试页面。是否有可能获得包含属性数据的每个元素(段落)-...?
之后,我需要将此属性与内部HTML进行比较,但我不知道该怎么做。
首先,您需要检索您感兴趣的所有元素的表示。这可以通过 casper.getElementsInfo(selector)
:
来完成
var elements = casper.getElementsInfo("p[data-whatever]");
这将为您提供页面上具有 data-whatever
属性集的所有 <p>
元素。如果你想通过 data-whatever
属性的值过滤它,那么你需要根据你的需要使用 attribute selectors。
getElementsInfo()
函数包含非常有用的信息,但不包含您要使用的实际元素。它只包含一个数组表示。
您可以遍历这些元素表示并 运行 您对它们的操作。你说你要"compare this attribute with inner 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()
, because PhantomJS (which CasperJS is built upon) has two contexts and the page context is sandboxed. Also, you cannot return DOM nodes from the page context.
内部执行此操作
我正在尝试使用 CasperJS 测试页面。是否有可能获得包含属性数据的每个元素(段落)-...? 之后,我需要将此属性与内部HTML进行比较,但我不知道该怎么做。
首先,您需要检索您感兴趣的所有元素的表示。这可以通过 casper.getElementsInfo(selector)
:
var elements = casper.getElementsInfo("p[data-whatever]");
这将为您提供页面上具有 data-whatever
属性集的所有 <p>
元素。如果你想通过 data-whatever
属性的值过滤它,那么你需要根据你的需要使用 attribute selectors。
getElementsInfo()
函数包含非常有用的信息,但不包含您要使用的实际元素。它只包含一个数组表示。
您可以遍历这些元素表示并 运行 您对它们的操作。你说你要"compare this attribute with inner 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()
, because PhantomJS (which CasperJS is built upon) has two contexts and the page context is sandboxed. Also, you cannot return DOM nodes from the page context.