我如何用木偶操纵者从iframe中抓取文字。
作为一个简单的可重现示例,请从此网址的iframe中抓取This is a paragraph
https://www.w3schools.com/js/tryit.asp?filename=tryjs_events
答案 0 :(得分:3)
要在木偶操作员中抓取iframe
的文字,您可以使用木偶操作员page.evaluate
在返回iframe
的页面的上下文中评估JavaScript的内容。
这样做的步骤是:
iframe
元素iframe
' document
个对象。 document
对象阅读iframe
的HTML 我写了这个程序,从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。