点击每个元素,然后用马夫刮

Click each element then scrape with horseman

本文关键字:然后 马夫刮 元素      更新时间:2023-09-26

我正在使用一个名为hordman的node.js模块从包含JavaScript的站点中抓取一些数据。我很难弄清楚如何点击每个span元素,如果其中包含某个元素,在这种情况下是table。这将扩展该元素并生成可用于抓取的数据,而这些数据现在是隐藏的。

我现在拥有的

horseman
    .open(url)
    .click("span.title")
    .waitforSelector("span.title")
    .then(scrape)

刮擦功能:

function scrape() {
    return new Promise(function (resolve, reject) {
        return getLinks()
            .then(function (newLinks) {
                links = links.concat(newLinks);

                if (links.length < 1)
                    return horseman
                        .then(scrape);
            }
            })
        .then(resolve);
});
    }

以及getlinks函数()

var links = [];
function getLinks() {
    return horseman.evaluate(function () {
        var links = [];
        $("span.title").each(function (item) {
            var link = {
                title: $(this).text()
            };
            links.push(link);
        });
        return links;
    });
}

我最初的想法是,在getLinks()函数中,我可以检查项是否包含表,然后单击并刮取,但不确定如何实现它。这个想法是扩展所有尚未扩展的跨度元素,这意味着数据是可见的,并且可以被抓取。我已经遇到了该怎么办的困难,所以任何帮助都会很棒!

以下代码:

    horseman
        .open(url)
        .click("span.title")
        .waitforSelector("span.title")
        .then(scrape)

将不起作用,因为CCD_ 1骑手动作仅处理单个元素。相反,您可以尝试以下代码,这些代码将适用于许多元素:

    horseman
        .open(url)
        .evaluate(clickItems)
        .waitforSelector("span.title XXX")
        .then(scrape)

其中:

  • XXX应该是span.title内内容的选择器(因此waitForSelector实际上会等待)。例如,让我们考虑一下这个标记:

    <span class="title"><!-- this is the clickable item --> <table>...</table> <div class="show-on-click">Blah blah</div> </span>

在上面的示例中,您将使用.waitForSelector('span.item .show-on-click')。在数据出现之前,您必须找到哪个选择器不存在。(或改用.wait(1000)

  • clickItem函数定义如下(我看到你使用jQuery,所以我也会这样做)

    function clickItems() {
        var $items = $('span.title:has(table)');
        $items.each(function(index, $item) {
            $item.click();
        });
    }
    

注意:这将单击所有元素span.title。您可以修改click元素,在每个$item中添加一个表存在性测试,但我想,如果其他click没有做任何事情,您可以省略它