ElementHandle与DOM元素有何不同?

Ata*_*v32 4 javascript puppeteer

页面上的文档。$(selector)说它返回一个包含ElementHandle的Promise。

但是缺少ElementHandle的文档。

它说它“代表DOM元素”,但是那真的意味着什么?如果代表DOM,为什么不能检查ElementHandle的内容?

它还说:“除非处置了句柄,否则防止垃圾回收中的DOM元素。” 如果浏览器仍在页面上,为什么DOM元素会被垃圾回收?


之所以出现这种情况,是因为我认为从页面上的元素中获取文本很简单,所以我尝试了一下,

const text = await page.$('#text').textContent;
Run Code Online (Sandbox Code Playgroud)

回来了undefined。所以我尝试了

const text = await page.$('#text').textContent();
Run Code Online (Sandbox Code Playgroud)

这引发了错误。

原来正确的方法是

const text = await page.evaluate(() => document.querySelector('#text').textContent);
Run Code Online (Sandbox Code Playgroud)

Eve*_*tss 5

使用ElementHandle,您仍然可以以textContent“操纵者方式” 访问属性,例如。首先,您必须.getProperty()打开ElementHandle,然后将其转换为.jsonValue()。请记住,所有这些操作都会返回错误,因此您应该await对所有这些操作进行如下操作:

await (await (await page.$('#text')).getProperty('textContent')).jsonValue();
Run Code Online (Sandbox Code Playgroud)

这是完整的工作示例:

const puppeteer = require('puppeteer');

const html = `
<html>
  <body>
    <div id="text">Sample content</div>
  </body>
</html>`;

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto(`data:text/html,${html}`);

  const text = await page.evaluate(() => document.querySelector('#text').textContent);
  const text2 = await (await (await page.$('#text')).getProperty('textContent')).jsonValue();

  console.log(text);
  console.log(text2);

  await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

  • 您没有回答这个问题:什么是 ElementHandle (5认同)