【问题标题】:Horseman - clicking multiple buttons then grabbing data - How?Horseman - 单击多个按钮然后抓取数据 - 如何?
【发布时间】:2017-10-11 22:23:24
【问题描述】:

我想解析一个可以有任意数量按钮的网页。我想单击所有按钮并从每次按下按钮时获取一些结果数据。我不知道该怎么做。到目前为止,我的骑士代码:

horse
 .on('resourceError', function(err) {
   console.dir(err);
   horse.close();
})
.userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
.open('https://www.example.com')
.click('#agree')
.click('input[class="button"]')
.waitForSelector('#address')
.type('#address', 'blah blah')
.click('#button-search-address')
.wait(3000)
.evaluate(function() {
  var btns=[];
  $('[data-agency-code]').each(function(i) {
    btns.push({dac: $(this).attr('data-agency-code')});
  });
  return btns;
})
.then(?????) 

所以我在 btns 数组中有所有机构代码。现在我需要像这个伪代码一样遍历所有按钮:

var resData=[]; 
jQuery.each(btns, function(i, val) {
  ... 
  .click('[data-agency-code]'+val.dac)
  .waitForSelector('#data-agency-data')
  .grab data like:
     resData.push({email: $('#agency-email').val(), phone: $('#agency-phone').val()});
});      

无法找出执行此循环的骑士代码。谢谢。

【问题讨论】:

    标签: node.js web-scraping promise node-horseman


    【解决方案1】:

    从 Horseman Github 页面上的第 85 期开始工作。

    下面是遍历页面上所有按钮的代码:

    horse
      .on('resourceError', function(err) {
        console.dir(err);
        horse.close();
      })
      .userAgent('Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko/20100101 Firefox/27.0')
      .open('https://www.example.com')
      .click('#agree')
      .click('input[class="button"]')
      .waitForSelector('#address')
      .type('#address', 'blah blah')
      .click('#button-search-address')
      .wait(3000)
      .evaluate(function() {
        var btns=[];
        $('[data-agency-code]').each(function(i) {
          btns.push({dac: $(this).attr('data-agency-code')});
        });
        return btns;
      })
      .then(function(btns) {
        if (btns.length == 0)
          horse.close();
        console.log(btns);
        var chain = horse;
        for(var i=0; i < btns.length; i++) {
          chain = chain
            .click('[data-agency-code='+btns[i].dac+']')
            .wait(2000)
            .evaluate(function() {
               return {
                 name: $('some selector').text().trim(),
                 email: $('some selector').text(),
                 www: $('some selector').text() 
               }
             })
             .then(function(aobj) {
               agya.push(aobj);
             })
        }
        return chain;
      })
      .then(function(chain) {
        console.log(agya);
      })
      .close();
    

    现在我在 agya 数组中拥有所有机构和信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 2016-11-16
      • 2015-01-05
      • 1970-01-01
      • 2021-04-09
      • 2021-12-10
      相关资源
      最近更新 更多