如何关注CasperJS中的所有链接

How to follow all links in CasperJS?

本文关键字:链接 何关注 CasperJS      更新时间:2023-11-15

我在DOM中单击所有基于JavaScript的链接并保存输出链接的形式为

<a id="html" href="javascript:void(0);" onclick="goToHtml();">HTML</a>

以下代码运行良好:

var casper = require('casper').create();
var fs = require('fs');
var firstUrl = 'http://www.testurl.com/test.html';
var css_selector = '#jan_html';
casper.start(firstUrl);
casper.thenClick(css_selector, function(){
    console.log("whoop");
});
casper.waitFor(function check() {
    return this.getCurrentUrl() != firstUrl;
}, function then() {
    console.log(this.getCurrentUrl());
    var file_title = this.getTitle().split(' ').join('_') + '.html';
    fs.write(file_title, this.getPageContent());
});
casper.run();

但是,如何使用选择器"a"并单击所有可用链接和保存内容?我不知道如何让clickWhileSelector从选择器中删除节点,就像这里所做的那样:点击与选择器匹配的所有链接

我有一个脚本,它将首先从一个页面获取所有链接,然后将"href"属性保存到一个数组,然后迭代该数组,然后逐个打开每个链接并返回url:

var casper = require('casper').create({
    logLevel:"verbose",
    debug:true
});
var links;
casper.start('http://localhost:8000');
casper.then(function getLinks(){
     links = this.evaluate(function(){
        var links = document.getElementsByTagName('a');
        links = Array.prototype.map.call(links,function(link){
            return link.getAttribute('href');
        });
        return links;
    });
});
casper.then(function(){
    this.each(links,function(self,link){
        self.thenOpen(link,function(a){
            this.echo(this.getCurrentUrl());
        });
    });
});
casper.run(function(){
    this.exit();
});
如果所有链接都有一个有意义的href属性(实际URL),那么

rusln的答案非常有效。如果您想单击每个也触发javascript函数的a,您可能需要以其他方式对元素进行迭代。

我建议使用stijn de ryck中的XPath生成器作为元素。

  1. 然后,您可以对页面上的所有XPath进行采样
  2. 然后打开具有XPath的每个a的页面,并通过XPath单击它
  3. 如果是单页应用程序,请稍等
  4. 做点什么
var startURL = 'http://localhost:8000',
    xPaths
    x = require('casper').selectXPath;
casper.start(startURL);
casper.then(function getLinks(){
    xPaths = this.evaluate(function(){
        // copied from https://stackoverflow.com/a/5178132/1816580
        function createXPathFromElement(elm) {
            var allNodes = document.getElementsByTagName('*'); 
            for (var segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) { 
                if (elm.hasAttribute('id')) { 
                        var uniqueIdCount = 0; 
                        for (var n=0;n < allNodes.length;n++) { 
                            if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++; 
                            if (uniqueIdCount > 1) break; 
                        }; 
                        if ( uniqueIdCount == 1) { 
                            segs.unshift('id("' + elm.getAttribute('id') + '")'); 
                            return segs.join('/'); 
                        } else { 
                            segs.unshift(elm.localName.toLowerCase() + '[@id="' + elm.getAttribute('id') + '"]'); 
                        } 
                } else if (elm.hasAttribute('class')) { 
                    segs.unshift(elm.localName.toLowerCase() + '[@class="' + elm.getAttribute('class') + '"]'); 
                } else { 
                    for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) { 
                        if (sib.localName == elm.localName)  i++; }; 
                        segs.unshift(elm.localName.toLowerCase() + '[' + i + ']'); 
                }; 
            }; 
            return segs.length ? '/' + segs.join('/') : null; 
        };
        var links = document.getElementsByTagName('a');
        var xPaths = Array.prototype.map.call(links, createXPathFromElement);
        return xPaths;
    });
});
casper.then(function(){
    this.each(xPaths, function(self, xpath){
        self.thenOpen(startURL);
        self.thenClick(x(xpath));
        // waiting some time may be necessary for single page applications
        self.wait(1000);
        self.then(function(a){
            // do something meaningful here
            this.echo(this.getCurrentUrl());
        });
        // Uncomment the following line in case each click opens a new page instead of staying at the same page
        //self.back()
    });
});
casper.run(function(){
    this.exit();
});