如何从 iFrame 中的元素捕获动态内容?

How to capture dynamic content from element inside an iFrame?

当我尝试从 iFrame 内的元素捕获文本时,元素内容每秒都在变化,我得到“未定义”。我可能做错了什么?

代码:

const { firefox } = require('playwright');
const fs = require('fs');
var url = 'http://jsfiddle.net/6vnam1jr/1/show';
var section_path = 'xpath=/html/body/div/div/div/section';
var iframe_path = 'xpath=/html/body/div/iframe';
var text_path = 'xpath=//html/body/div[2]/div[2]';
async function getElementText(browser,page){
  await page.goto(url);
  await page.click(section_path);
  
  const frame = await page.$(iframe_path);
  const contentFrame = await frame.contentFrame();
  await sleep(1000);
  let handle = await contentFrame.$eval(text_path);
  console.log(handle)
  
  // try again
  await sleep(1000);
  handle = await contentFrame.$eval(text_path);
  console.log(handle)
  
  closeBrowser(browser);
}
async function closeBrowser(browser){
  await browser.close();
}
function sleep(ms) {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
}
(async () => {
  const browser = await firefox.launch({ headless: false });
  const page = await browser.newPage();
  getElementText(browser,page);
})();```

感谢重现。 frame.$eval 是一个 API 到 运行 浏览器中的一个 JS 函数,它将元素作为参数。

我相信您正在寻找的是用于此目的的 ElementHandle to this element. You can use frame.waitForSelector or frame.$。我已经确认它们不是未定义的。

// ...
let handle = await contentFrame.waitForSelector(text_path);