ale*_*nco 2 javascript node.js puppeteer
我想让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`)
})
})()
Run Code Online (Sandbox Code Playgroud)
但我收到这个错误:
Run Code Online (Sandbox Code Playgroud)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`)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3794 次 |
| 最近记录: |