Не удается передать элементы в цикле for для печати двух элементов вместе - PullRequest
2 голосов
/ 09 апреля 2019

Я написал скрипт на node, чтобы вычистить titles и urls для заголовков различных сообщений со целевой страницы веб-страницы, а затем извлечь profile name каждого пользователя с его внутренней страницы. , Единственное, что я не могу решить, это напечатать две вещи items и output внутри for loop.

Как я могу передать items в for loop, чтобы скрипт мог одновременно печатать items и output?

Я пробовал как:

var request = require('request');
var cheerio = require('cheerio');

const url = 'https://stackoverflow.com/questions/tagged/web-scraping';
const host = 'https://stackoverflow.com';

function getPosts() {
    request(url, function(error, response, html) {
        if (!error && response.statusCode == 200) {
            var $ = cheerio.load(html);
            let linkstorage = [];
            $('.summary .question-hyperlink').each(function() {
                var items = $(this).text();
                var links = host + $(this).attr("href");
                linkstorage.push(links);
            });

            for (const newlink of linkstorage) {
                request(newlink, function(error, response, html) {
                    if (!error && response.statusCode == 200) {
                        var $ = cheerio.load(html);
                        var output = $(".user-details a").eq(0).text();
                        console.log(output);
                    }
                });
            }
        }
    });
}
getPosts();

1 Ответ

0 голосов
/ 09 апреля 2019

Объявления переменных и присваивания могут быть разделены в JavaScript.Вы можете определить переменную items вне области цикла for, для которой назначено

// define it outside the jquery function scope
       let items;

      $('.summary .question-hyperlink').each(function(){
        items = $(this).text();
        ...
      });

      for (const newlink of linkstorage){
        request(newlink,function(error,response,html){
          if (!error && response.statusCode == 200){
          var $ = cheerio.load(html);
          var output = $(".user-details a").eq(0).text();
          console.log(output);
          console.log(items); // It is visible in this scope
          }
        });
      }
    }
...