簡體   English   中英

如何從木偶/劇作家 JSelement 節點中刪除一個孩子,然后獲取 innerText

[英]How to remove a child from a puppeteer/playwright JSelement node and then fetch innerText

我可以使用 playwright/puppeteer 獲取單元格。 我想分別捕獲以下兩個值 - 日期和狀態。

我有以下代碼:

  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>

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

您可以嘗試使用以下內容獲取瀏覽器上下文中的所有數據( .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(); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM