我想让木偶师根据名为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`)
}