【问题标题】:How to remove a child from a puppeteer/playwright JSelement node and then fetch innerText如何从 puppeteer/playwright JSelement 节点中删除子节点,然后获取 innerText
【发布时间】:2021-09-25 00:08:00
【问题描述】:

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

我有以下代码:

  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 不是函数

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>

【问题讨论】:

  • 为什么要在自动化中从 dom 中删除一个节点?你想达到什么目的?
  • 可能有很多用例。在只读抓取中,我不在乎这个子节点会发生什么,我只想要父节点的值而不需要这个子节点内部的内容。

标签: javascript puppeteer playwright htmlelements


【解决方案1】:

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

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

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(); }

【讨论】:

  • 谢谢!我试图继续使用 API 调用而不使用评估。但看起来这可能是它唯一的工作方式。我会尝试并报告。
  • @Curious101 我认为这不是唯一的方法,但有时它是最简单最快的方法:JS处理API在大多数情况下看起来非常冗长和繁琐。我认为你可以在这种情况下使用它,但它会更长更复杂的代码。
  • 谢谢。成功了,我接受了你的回答。感谢您的努力。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
  • 2019-06-26
  • 1970-01-01
  • 1970-01-01
  • 2017-02-04
  • 1970-01-01
相关资源
最近更新 更多