首页 > 解决方案 > Puppeteer - 如何在 page.evaluate() 中使用 page.click()

问题描述

我正在刮一张桌子,每一行都有一个按钮来显示一个带有信息的模式。我需要从模式中为每一行抓取信息,但我不知道如何打开模式。我已经尝试在 page.evaluate() 中使用 page.click(selector) 但它没有用。

我已经测试了下一个代码。

const users = await page.evaluate(() => {
  const usersTable = Array.from(document.querySelectorAll('table#grilla > tbody > tr'))
  const userInfo = usersTable.map(async userTable => {
    await page.click('td > a#modificar-2')
    await page.click('div > button[type=submit].close')
    const username = userTable.children[2].innerText
    const firstName = userTable.children[4].innerText
    const lastName = userTable.children[5].innerText
    const email = userTable.children[6].innerText
    const estado = userTable.children[7].innerText
    const fullName = firstName + lastName
    return { username, fullName, email, estado }
  })
  return userInfo
})

我不知道如何在 page.evaluate() 中传递 page.click() 或其他选项

标签: web-scrapingpuppeteer

解决方案


如果你使用page.evaluate()你将上下文从节点 puppeteer 切换到浏览器,那么你必须使用 JS 原生函数,比如 click: document.querySelector(selector).click()

如果您遇到错误,例如Error: Evaluation failed: TypeError: Cannot read property 'click' of null您想要单击的元素可能不在页面上(或者它被隐藏或其他)。


推荐阅读