Web抓取函数返回“未定义”,但是当我使用console.log时可以使用

时间:2019-10-25 20:47:14

标签: javascript node.js web-scraping callback

const cheerio = require("cheerio");
const request = require("request");


function GetPhysicalDmg(champname) {
        request("https://champion.gg/champion/" + champname, (error, response, html) => {
        let matchupData = {}
        if (!error && response.statusCode == 200)
        {
            var $ = cheerio.load(html);
            var row = $('.footer-attr');
            var divvoorscript = row.prev().prev().html();
            eval(divvoorscript);
            var physicaldmg = Number(matchupData.championData.dmgComposition.physicalDmg);
            var magicdmg = Number(matchupData.championData.dmgComposition.magicDmg);
            var truedmg = Number(matchupData.championData.dmgComposition.trueDmg);
            return physicaldmg;
        }
    }); 
}
console.log(GetPhysicalDmg("Nautilus"))

以下在控制台中记录“未定义”。显然,这是因为request是一个异步函数,并且我尝试使用回调,但是无法理解其工作原理。

function GetPhysicalDmg(champname) {
        request("https://champion.gg/champion/" + champname, (error, response, html) => {
        let matchupData = {}
        if (!error && response.statusCode == 200)
        {
            var $ = cheerio.load(html);
            var row = $('.footer-attr');
            var divvoorscript = row.prev().prev().html();
            eval(divvoorscript);
            var physicaldmg = Number(matchupData.championData.dmgComposition.physicalDmg);
            var magicdmg = Number(matchupData.championData.dmgComposition.magicDmg);
            var truedmg = Number(matchupData.championData.dmgComposition.trueDmg);
            console.log(physicaldmg);
        }
    }); 
}

这将按原样返回值。

1 个答案:

答案 0 :(得分:-1)

这就是我要做的:

const axios = require('axios');
const cheerio = require('cheerio');

const getPhysicalDmg = async champname => {
  let request = await axios.get("https://champion.gg/champion/" + champname)
  let matchupData = {}
  var $ = cheerio.load(request.data);
  var row = $('.footer-attr');
  var divvoorscript = row.prev().prev().html();
  eval(divvoorscript);
  var physicaldmg = Number(matchupData.championData.dmgComposition.physicalDmg);
  var magicdmg = Number(matchupData.championData.dmgComposition.magicDmg);
  var truedmg = Number(matchupData.championData.dmgComposition.trueDmg);
  return physicaldmg;
}

;(async function(){
  console.log(await getPhysicalDmg("Nautilus"))
})()

希望这种方式不那么令人困惑,至少对我而言。同样,在中间进行评估通常是一个非常糟糕的主意。