繁体   English   中英

如何在horseman的[node.js的幻像] validate()中使用jquery each()函数来模拟多次点击?

[英]How to use jquery each() function within horseman's [phantom for node.js] evaluate() to simulate multiple clicks?

好吧,我需要使用循环的骑手点击许多链接。 例如HTML文件:

<ul class="conn-list">
   <li><a> link 1 </a></li>
   <li><a> link 2 </a></li>
   <li><a> link 3 </a></li>
</ul>

我已经尝试过这样的事情(.js文件[使用node.js]):

var Horseman = require("node-horseman");
var horseman = new Horseman();
var $ = require ("jquery");

horseman.viewport(3200, 1800)
    .open('url')

    /* some code to navigate the headless browser*/

    .evaluate(function clickLinks() {
        var $links = $("a"); //I am supposing that are not other <a> tags on the page.
        $links.each(function (index, $links) {
            $(this).click();

            horseman.waitForNextPage()
                .wait(5000) //just to ensure that all the page loads before the print.
                .screenshot("new_page", index, ".png") //just to know if it works.
        });
    })

仅此而已,它可以编译但不使用scheenshots也不访问超链接。.我不知道,也许答案是使用horseman.js的多个选项卡支持。欢迎任何新手帮助! :D谢谢您的时间!

Horseman的.evaluate()方法采用一个函数,然后将其转换为字符串并注入到页面中。 这意味着该函数不知道它之外的任何东西(例如前horseman )。

您将得到一个非常无用的错误,其中包含:

global code
evaluateJavaScript@[native code]

您想在传递给.evaluate(fn)的函数中返回链接的URL,将这些URL带回到节点进程中并在那里循环。

由于Horseman是建立在Bluebird Promise库之上的,因此您只需调用.then() 因此,如下所示:

horseman.viewport(3200, 1800)
  .open('url')
  .evaluate(function clickLinks() {
    var $links = $("a"); //I am supposing that are not other <a> tags on the page.
    return $links.map(function (index, $links) {
      return $(this).attr('href');
    }).get();
  })
  .then(async function (hrefs){
    // this uses async/await, but you can use some recursive function or some other async looping logic
    for(var href of hrefs) {
      // use the .open() method with the gathered href's
      await horseman.open(href)
        .wait(5000) //just to ensure that all the page loads before the print.
        .screenshot("new_page", index, ".png") //just to know if it works.
    }
  })

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM