我想做Puppeteer根据名为 tabs
的数组中的项目数单击一些选项卡:
;(async () => {
const browser = await puppeteer.launch({
headless: true
})
const page = await browser.newPage()
await page.goto(`https://www.example.com`)
const tabs = ['tab1', 'tab2', 'tab3']
tabs.forEach((tab, index) => {
await page.click(`.postab-container li:nth-of-type(${ index + 1 }) a`)
})
})()
但我收到此错误:
await page.click(`.postab-container li:nth-of-type(${ index + 1 }) a`) ^^^^ SyntaxError: Unexpected identifier
看起来像forEach
声明搞砸了page
.
正确的做法是什么?
最佳答案
forEach 内部的函数不是 async
函数,因此您不能使用 await
,但即使您将其更改为 async
使用函数时,您不会得到预期的结果(forEach 将立即生成所有请求,而不是 await
每个异步函数
)。请改用 for 循环。
for(let index =0;index<tabs.length;++index){
let tab = tabs[index];
await page.click(`.postab-container li:nth-of-type(${ index + 1 }) a`)
}
关于javascript - 如何在 forEach 循环中使用 Puppeteer 的 page.click ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59769686/