简体   繁体   中英

How to pass new options with cheerio with a loop function

Im tryin to call goforit() function with new options each time the function is finished. I just want to modify the value of actualpage pass it to baseuri.

Can you help ? I turn around like a fish

actually the function return the same options, but the value actualpage is changing

 const rp = require('request-promise'); const cheerio = require('cheerio'); var cookiejar = rp.jar(); var actualpage = 1; var baseuri = 'https://www.website.page=' + actualpage; var options = { uri: baseuri, headers: { 'Host': 'www.website.com', 'Connection': 'keep-alive' }, jar: cookiejar, transform: function(body) { return cheerio.load(body); } }; goforit() function goforit() { actualpage = actualpage + 1 baseuri = 'https://www.website.com' + actualpage; setTimeout(function() { rp(options) .then(($) => { var arr = 0 arr = $('.bt__media__content p') var fruits = $('.bt__ment p'); fruits.each(function(i, elem) { console.log(fruits[i].children[0].attribs) }); goforit() }) .catch((err) => { console.log(err); }); }, 3000); } 

I assume you are using latest node version.

options = {...options, uri: baseuri}

options can be updated by using spread operator.

add this line,

 const rp = require('request-promise'); const cheerio = require('cheerio'); var cookiejar = rp.jar(); var actualpage = 1; var baseuri = 'https://www.website.page=' + actualpage; var options = { uri: baseuri, headers: { 'Host': 'www.website.com', 'Connection': 'keep-alive' }, jar: cookiejar, transform: function(body) { return cheerio.load(body); } }; goforit() function goforit() { actualpage = actualpage + 1 baseuri = 'https://www.website.com' + actualpage; // add this line options = {...options, uri: baseuri} setTimeout(function() { rp(options) .then(($) => { var arr = 0 arr = $('.bt__media__content p') var fruits = $('.bt__ment p'); fruits.each(function(i, elem) { console.log(fruits[i].children[0].attribs) }); goforit() }) .catch((err) => { console.log(err); }); }, 3000); } 

you have to increment the value of (actualpage) before function end like this

function goforit() {
    actualpage = actualpage + 1
    baseuri = 'https://www.website.com' + actualpage;

   setTimeout(function() {
       rp(options).then(($) => {
        var arr = 0
        arr = $('.bt__media__content p')
        var fruits = $('.bt__ment p');
        fruits.each(function(i, elem) {
        console.log(fruits[i].children[0].attribs)
    });
    actualpage++;
    goforit()

  })
  .catch((err) => {
    console.log(err);
  });
 }, 3000);
}

so when your function is call ( actualpage ) is incremente.

hope it helps..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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