javascript - 将评估结果保存到变量 - 噩梦般的网络抓取
问题描述
这是基本代码...我跳过了一些要求语句...此代码在控制台中打印出一个链接。我想将该链接存储在一个变量中以供以后使用。
app.post('/search', function(req, res){
const val = req.body.searchText;
const nightmare = new Nightmare({
show: true
});
let aa;
(async function() {
await nightmare
.goto('https://google.com/')
.insert('#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input', val + ' + MuzzMusic.com')
.click('#tsf > div:nth-child(2) > div.A8SBwf > div.FPdoLc.tfB0Bf > center > input.gNO89b')
.click('#rso > div:nth-child(1) > div > div.r > a > h3')
.evaluate(() => {
aa = document.querySelector('#post-54106 > div > div.entry-content > p:nth-child(4) > a').href
return aa
})
.end()
.then(console.log)
.catch((err) => {
console.log(err)
})
console.log('aa ==== ' + aa) //checking if it works
})
解决方案
尝试这个:
app.post('/search', async function(req, res){
const val = req.body.searchText;
const nightmare = new Nightmare({
show: true
});
let aa
try {
aa = await nightmare
.goto('https://google.com/')
.insert('#tsf > div:nth-child(2) > div.A8SBwf > div.RNNXgb > div > div.a4bIc > input', val + ' + MuzzMusic.com')
.click('#tsf > div:nth-child(2) > div.A8SBwf > div.FPdoLc.tfB0Bf > center > input.gNO89b')
.click('#rso > div:nth-child(1) > div > div.r > a > h3')
.evaluate(() => document.querySelector('#post-54106 > div > div.entry-content > p:nth-child(4) > a').href)
.end()
} catch (error) {
console.log(error)
}
console.log('aa ==== ' + aa) //checking if it works
})