2017-10-11 81 views
0

我想解析一个可以有任意数量的按钮的网页。我想单击所有按钮,并从每个按钮中获取一些结果数据。我不知道如何做到这一点。我的马人代码,到目前为止:轻骑兵 - 点击多个按钮然后抓取数据 - 如何?

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()}); 
});  

想不通时的骑手代码来完成这个循环。谢谢。

回答

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阵列中的所有机构和信息。

相关问题