【问题标题】:How to capture dynamic content from element inside an iFrame?如何从 iFrame 内的元素中捕获动态内容?
【发布时间】:2021-01-16 09:55:44
【问题描述】:

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

【问题讨论】:

    标签: iframe playwright


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2013-01-27
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      • 2018-10-30
      相关资源
      最近更新 更多