8

CasperJS を使用してクリックをシミュレートする必要があるリンクのリストがあります。それらはすべて同じクラスを共有しています。

ただしthis.click('.click-me')、最初のリンクをクリックするだけです。

すべてのリンクをクリックする適切な方法は何ですか? リンクの数を取得してからループevaluate()を使用する必要があるのではないかと考えています。forしかしevaluate()、リンクの数を使用すると、メッセージを使用してやり取りする必要があり、複雑に思えます。

より良い方法はありますか?

4

3 に答える 3

15

これを達成するために nth-child() セレクターを使用することになりました。方法は次のとおりです...

ページ:

<ul id="links">
  <li><a href="#1">1</a></li>  
  <li><a href="#2">2</a></li>  
  <li><a href="#3">3</a></li>  
</ul>

脚本:

casper.then(function() {
  var i = 1;
  this.repeat(3, function() {
    this.click('#links li:nth-child(' + i + ') a');
    i++;
  });
});

明らかに繰り返しを使用する必要はありませんが、反復手法は機能するはずです。

于 2014-02-14T02:53:43.057 に答える
8

CasperJS ML およびレコードで提案されているように、可能な実装は次のclickWhileSelectorとおりです。

var casper = require('casper').create();

casper.clickWhileSelector = function(selector) {
    return this.then(function() {
        if (this.exists(selector)) {
            this.echo('found link: ' + this.getElementInfo(selector).tag);
            this.click(selector);
            return this.clickWhileSelector(selector);
        }
        return this.echo('Done.').exit();
    });
}

casper.start().then(function() {
    this.page.content =
        '<html><body>' +
        '<a href="#" onclick="this.parentNode.removeChild(this);return false;">link 1</a>' +
        '<a href="#" onclick="this.parentNode.removeChild(this);return false;">link 2</a>' +
        '<a href="#" onclick="this.parentNode.removeChild(this);return false;">link 3</a>' +
        '</body></html>';
});

casper.clickWhileSelector('a').run();

それは与える:

$ casperjs c.js
found link: <a href="#" onclick="this.parentNode.removeChild(this);return false;">link 1</a>
found link: <a href="#" onclick="this.parentNode.removeChild(this);return false;">link 2</a>
found link: <a href="#" onclick="this.parentNode.removeChild(this);return false;">link 3</a>
Done.
于 2013-02-04T22:23:09.863 に答える
1

無限ループを回避するために、他の応答を混合します(私のアイテムはタグ内で連続していたので、これは私にとってはうまくいきました):

casper.clickWhileSelector = function(selector, i) {
    return this.then(function() {
        i = i || 1;
        selectorNth = selector+':nth-child(' + i + ')';

        if (this.exists(selectorNth)) {
            this.echo('found link: '+this.getElementInfo(selectorNth).tag);
            this.click(selectorNth);
            return this.clickWhileSelector(selector, i+1);
        }
        return this.echo('Done.').exit();
    });
}

それが役に立てば幸い!

ルイス。

于 2016-08-08T21:58:15.083 に答える