0

我可以使用剧作家/木偶师来获取单元格。我想分别捕获以下两个值 - 日期和状态。

我有以下代码:

  let allCells = await allRows[0].$$('[role="cell"]');

  let ele = await allCells[0].$('.description');
  let status = await (await ele.getProperty("innerText")).jsonValue();
       // I can get the status as 'uploaded' just fine using this

  allCells[0].removeChild(ele);    // this throws an error

  let uploadDate = await (await allCells[0]("innerText")).jsonValue();      

它抛出的错误是: TypeError: allCells[0].removeChild is not a function

console.log( allCells[0] ) 返回:JSHandle@…。

这是 HTML 的相关部分:

<html>
<body>
  <div role="cell" class="cell-body">
     <!---->Jul 11, 2021
     <div class="description">
        uploaded
     </div>
  </div>
</body>
</html>
4

1 回答 1

1

不幸的是,您不能.removeChild在 JS 上调用 Web API 方法 () 或在 puppeteer (Node.js) 上下文中调用元素句柄。

您可以尝试使用以下方式获取浏览器上下文中的所有数据(.childNodes[0]将只为您提供第一个文本节点,直到<div class="description">元素):

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch();

const html = `
  <html>
  <body>
    <div role="cell" class="cell-body">
       Jul 11, 2021
       <div class="description">
          uploaded
       </div>
    </div>
  </body>
  </html>`;

try {
  const [page] = await browser.pages();

  await page.goto(`data:text/html,${html}`);

  const data = await page.evaluate(() => {
    const date = document.querySelector('div.cell-body').childNodes[0].textContent.trim();
    const description = document.querySelector('div.description').innerText;
    return [date, description];
  });
  console.log(data);
} catch (err) { console.error(err); } finally { await browser.close(); }
于 2021-07-16T18:57:19.423 回答