代码之家  ›  专栏  ›  技术社区  ›  wyc

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

  •  0
  • wyc  · 技术社区  · 6 年前

    我想 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 .

    正确的方法是什么?

    0 回复  |  直到 6 年前
        1
  •  5
  •   Cody Geisler    6 年前

    forEach内部的函数不是 async 所以你不能使用 await ,但即使你把它改成了 异步的 函数,您将无法得到预期的结果(forEach将一次生成所有请求,而不是 等候 每个 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`)
      }