如何在node.js和nightmare.js中使用超出其范围的变量(网络抓取)
当我尝试使用await范围之外的变量“downloadLink”时,它以未定义的形式返回。
app.post('/search', function(req, res){
const val = req.body.searchText;
const nightmare = new Nightmare({
show: true
});
(async function() {
const downloadLink = await nightmare
.viewport(1200, 700)
.goto('https://google.com/')
.insert('#selector0')
.click('#selector1')
.click('#selector2')
.evaluate(() => document.querySelector('#selector3').href)
.end()
.catch((err) => {
console.log(err)
})
console.log('download link ' + downloadLink) //this line prints a string
})();
console.log('download link ' + downloadLink) //this line returns undefined
})
我可以在其范围之外使用“downloadLink”并使用后一行代码进行打印吗?
最佳答案
Express支持异步处理程序,因此您可以像这样重构您的方法。无需将代码置于异步IIFE下。
app.post('/search', async function(req, res){
try {
const val = req.body.searchText;
const nightmare = new Nightmare({
show: true
});
const downloadLink = await nightmare
.viewport(1200, 700)
.goto('https://google.com/')
.insert('#selector0')
.click('#selector1')
.click('#selector2')
.evaluate(() => document.querySelector('#selector3').href)
.end()
console.log('download link ' + downloadLink);
} catch (err) {
console.error(err.message);
}
});
关于node.js - 如何在node.js和nightmare.js中使用超出其范围的变量(网络抓取),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63304720/