如何使用Puppeteer的页面。在forEach循环中单击?



我想让木偶师根据名为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每个async function(。请改用 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`)
}

最新更新