javascript - Puppeteer 无法获得完整的源代码

标签 javascript node.js web-scraping puppeteer

我正在使用 Node.js 和 Puppeteer 创建一个简单的抓取应用程序。 我试图抓取的页面是 this 。下面是我现在使用的代码。

const url = `https://www.betrebels.gr/el/sports?catids=122,40,87,28,45,2&champids=423,274616,1496978,1484069,1484383,465990,465991,91,71,287,488038,488076,488075,1483480,201,2,367,38,1481454,18,226,440,441,442,443,444,445,446,447,448,449,451,452,453,456,457,458,459,460,278261&datefilter=TodayTomorrow&page=prelive`
await page.goto(url, {waitUntil: 'networkidle2'});
let content: string = await page.content();
await page.screenshot({path: 'page.png',fullPage: true});
await fs.writeFile("temp.html", content);
//...Analyze the html and other stuff.

我得到的屏幕截图是this,这正是我所期望的。

另一方面,页面内容很少,并不代表图像上的数据。

我做错了什么吗?我是否没有正确等待 Javascript 完成?

enter image description here

最佳答案

该页面正在使用框架。您只能看到页面的主要内容(没有框架的内容)。要获取框架的内容,您需要首先找到框架(例如通过 page.$ ),然后通过 elementHandle.contentFrame 获取其框架句柄。然后您可以调用frame.content()获取框架的内容。

简单示例

const frameElementHandle = await page.$('#selector iframe');
const frame = await frameElementHandle.contentFrame();
const frameContent = await frame.content();

根据页面的结构,您需要对多个框架执行此操作才能获取所有内容,或者甚至需要对框架内的框架执行此操作(给定页面的情况似乎如此)。

读取所有框架内容的示例

下面是递归读取页面上所有框架内容的示例。

const contents = [];
async function extractFrameContents(pageOrFrame) {
  const frames = await pageOrFrame.$$('iframe');
  for (let frameElement of frames) {
    const frame = await frameElement.contentFrame();
    const frameContent = await frame.content();

    // do something with the content, example:
    contents.push(frameContent);

    // recursively repeat
    await extractFrameContents(frame); 
  }
}
await extractFrameContents(page);

关于javascript - Puppeteer 无法获得完整的源代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55994249/

相关文章:

javascript - 在nestjs中为不同位置和前缀提供多个静态文件?

javascript - promise 条件相等

python - 如何抓取这个 squawka 页面?

ruby - 使用 Kimurai gem 进行网页抓取

python-3.x - 如何使用 Selenium 按 class_name 从大学橄榄球数据中抓取图像 url 列表

javascript - 在 Titanium 中将 View 创建为弹出窗口

javascript - Three.js 中 Material 的灯无法正常工作

javascript - 如何将引号传递给javascript函数

node.js - 一种高效地逐一检查集合中所有数据的方法(nodejs、mongoose)

javascript - 如何获取我的 NPM 全局包的绝对路径?