如何访问其中范围外的变量?
How do I access variables outside a scope inside it?
这是我的代码,我正在尝试访问 page.evaulate 范围内的 anum 和 articleHTML。它说 anum 和 articleHTML 未定义
const num = context.params.event.content.split(' ').slice(1).join(' ')
let an = parseInt(num)
let anum = an - 1
let articleHTML = an + 1
let website = 'https://newkrunktimes.github.io/'
let browser = await puppeteer.launch();
let page = await browser.newPage()
await page.goto(website, {waitUntil: 'networkidle2'})
let data = await page.evaluate(() => {
articleTitle = document.getElementsByClassName("post-title h4 font-weight-bold")[anum].innerText
author = document.getElementsByClassName("post-supertitle")[anum].innerText
aImage = document.getElementsByClassName("img-fluid")[anum].currentSrc
aDesc = document.getElementsByClassName("post-content font-weight-light")[anum].innerText
artLink = document.querySelector(`a[class="ytlink"][target="_blank"][href="articles/article${articleHTML}.html"]`).href
return {
articleTitle,
author,
aImage,
aDesc,
artLink
}
})
这背后的原因是浏览器上下文中 page.evaluate() 运行 中的任何内容都不是定义 anum 和 articleHTML 的上下文(node.js 上下文).
我想你会在这里找到答案:
这是我的代码,我正在尝试访问 page.evaulate 范围内的 anum 和 articleHTML。它说 anum 和 articleHTML 未定义
const num = context.params.event.content.split(' ').slice(1).join(' ')
let an = parseInt(num)
let anum = an - 1
let articleHTML = an + 1
let website = 'https://newkrunktimes.github.io/'
let browser = await puppeteer.launch();
let page = await browser.newPage()
await page.goto(website, {waitUntil: 'networkidle2'})
let data = await page.evaluate(() => {
articleTitle = document.getElementsByClassName("post-title h4 font-weight-bold")[anum].innerText
author = document.getElementsByClassName("post-supertitle")[anum].innerText
aImage = document.getElementsByClassName("img-fluid")[anum].currentSrc
aDesc = document.getElementsByClassName("post-content font-weight-light")[anum].innerText
artLink = document.querySelector(`a[class="ytlink"][target="_blank"][href="articles/article${articleHTML}.html"]`).href
return {
articleTitle,
author,
aImage,
aDesc,
artLink
}
})
这背后的原因是浏览器上下文中 page.evaluate() 运行 中的任何内容都不是定义 anum 和 articleHTML 的上下文(node.js 上下文).
我想你会在这里找到答案: