从Iframe抓取文本

时间:2017-11-26 22:54:11

标签: javascript puppeteer

我如何用木偶操纵者从iframe中抓取文字。

作为一个简单的可重现示例,请从此网址的iframe中抓取This is a paragraph

https://www.w3schools.com/js/tryit.asp?filename=tryjs_events

2 个答案:

答案 0 :(得分:3)

要在木偶操作员中抓取iframe的文字,您可以使用木偶操作员page.evaluate在返回iframe的页面的上下文中评估JavaScript的内容。

这样做的步骤是:

  1. 抓住iframe元素
  2. 获取iframe' document个对象。
  3. 使用document对象阅读iframe的HTML
  4. 我写了这个程序,从link you provided抓取This is a paragraph

    const puppeteer = require("puppeteer");
    
    (async () => {
    
        const browser = await puppeteer.launch();
    
        const page = await browser.newPage();
        await page.goto('https://www.w3schools.com/js/tryit.asp?filename=tryjs_events');
    
        const iframeParagraph = await page.evaluate(() => {
    
            const iframe = document.getElementById("iframeResult");
    
            // grab iframe's document object
            const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    
            const iframeP = iframeDoc.getElementById("demo");
    
            return iframeP.innerHTML;
        });
    
        console.log(iframeParagraph); // prints "This is a paragraph"
    
        await browser.close();
    
    })();
    

答案 1 :(得分:1)

我知道这个问题已经有了答案,但是如果有人想采用另一种方法,您可以从iframe中获取内容,并使用cheerio遍历元素并获取您想要的任何元素的文本- you can find it here

相关问题