最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - check element using casperjs - Stack Overflow

programmeradmin0浏览0评论

I am trying to use casperjs to check if the following element exists in the DOM:

<b>Bar</b>

Is there a simple way to do that using selectors and casper.exists? The casperjs documentation makes it very unclear.

I am trying to use casperjs to check if the following element exists in the DOM:

<b>Bar</b>

Is there a simple way to do that using selectors and casper.exists? The casperjs documentation makes it very unclear.

Share Improve this question edited Oct 27, 2013 at 4:07 BoltClock 725k165 gold badges1.4k silver badges1.4k bronze badges asked Oct 26, 2013 at 21:42 JRRJRR 6,1626 gold badges46 silver badges67 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

The basic use of casper.exists() is to pass it a selector string and it'll return true or false to indicate whether any elements were found to match that selector.

In your case, however, the only practical selector that would find this element is b, so if you're specifically looking for a b element containing this text then you'll need to either specify some form of context (e.g. a parent element), or test this element's existence using XPath instead, which lets you test elements by their text content:

var x = require('casper').selectXPath;

if (casper.exists(x('//b[text()="Bar"]'))) {
    // <b>Bar</b> exists
}

if you need to check an other elements. Visit and learn how to find out an element by XPath and basisly follow the answer of BoltClock.

For example : check li with class="a-last"

 if (casper.exists(x('//li[@class="a-last"]'))) {
    console.log("find the element");    
 }

In case you're trying to select a vague or non-specific selector (No class or ID), using CSS Path worked for me, for example:

this.echo(this.getElementAttribute('html body div.main-container div.central-container div.articles-home h4));

In that case will print the title from the article. It works the same way when using it in exists().

发布评论

评论列表(0)

  1. 暂无评论