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

时间:2020-09-30 17:05:37

标签: iframe playwright

当我尝试从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);
})();```

1 个答案:

答案 0 :(得分:1)

感谢您的复制。 frame.$eval是在浏览器中运行JS函数的API,该函数将元素作为参数。

我相信您正在寻找的是此元素的ElementHandle。为此,您可以使用frame.waitForSelectorframe.$。我已经验证了它们不是未定义的。

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