【发布时间】:2020-08-22 22:36:42
【问题描述】:
我对 JavaScript 很陌生,试图理解异步函数的概念。所以,基本上我用噩梦为 RateMyProfessor 写了一个 webScraper。这是函数:
var Nightmare = require("nightmare"),
nightmare = Nightmare();
const baseURL =
"https://www.ratemyprofessors.com/search.jsp?queryBy=schoolId&schoolName=University+of+California+Santa+Barbara&schoolID=1077&queryoption=TEACHER";
const getRatingProfessor = (professorName) => {
let rating;
let nameSplitter = professorName.split(" ");
if (nameSplitter.length > 2) {
professorName = nameSplitter[0] + " " + nameSplitter[1];
}
nightmare
.goto(baseURL)
.click("#ccpa-footer > .close-this")
.type("#professor-name", professorName)
.wait(1000)
.evaluate(() => {
var resultList = document.querySelectorAll("a .rating");
//if no result is found
if (typeof resultList === "undefined" || resultList.length == 0) {
return "Not Found";
}
//Found the professor with exact name
if (resultList.length == 1) {
return document.querySelector("a > .rating").innerHTML;
}
//conficting similar professor names (rare case)
if (resultList.length >= 2) {
return "Cannot Determine";
}
})
.end()
.catch((err) => {
console.log(err);
})
.then((text) => {
rating = text;
console.log(professorName, text);
});
return rating;
};
console.log(getRatingProfessor("XXXXX"));
如果我运行这个程序,它会给出以下输出:
undefined
SomeProfName 4.8
该函数似乎在没有等待承诺的情况下将评级返回给 console.log。为什么函数不等待噩梦承诺得到解决。更重要的是,为什么评分的价值没有更新?还是已经更新但console.log不想等待函数?
抱歉,这些问题可能看起来很荒谬,但我非常感谢您的回答:0
【问题讨论】:
-
尝试使用 Async 并等待您的代码。资源:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript asynchronous web-scraping es6-promise nightmare