【问题标题】:Add onload to element without execution in Puppeteer将 onload 添加到元素而不在 Puppeteer 中执行
【发布时间】:2020-05-21 13:00:50
【问题描述】:

我正在 Puppeteer 中编写网络爬虫。页面准备好后,我必须重写 HTML 并向某些元素添加 onload

然而,Puppeteer 实际上执行了onload 事件。

原始元素:<link rel="stylesheet" href="style.css"/>

在 Puppeteer 中,使用 page.evaluate 方法我将以下内容运行到相应的元素:

elem.setAttribute('rel', 'preload');
elem.setAttribute('as', 'style');
elem.setAttribute('onload', "this.rel='stylesheet'");

预期输出:<link rel="preload" as="style" href="style.css" onload="this.rel='stylesheet'" />

实际输出:<link rel="stylesheet" as="style" href="style.css" onload="this.rel='stylesheet'"/>

有什么方法可以阻止 Puppeteer 中的 onload 或以某种方式使其工作?

另一种解决方案是在像 Cheerio 这样的 HTML 解析器中执行此部分。

【问题讨论】:

  • 请问您这样做的目的是什么? (可能还有另一种方法)如果这是一个爬虫,为什么还要使用样式表?
  • 我正在构建一个优化器,页面将在 Puppeteer 中打开,然后在 html 中完成一些更改并捕获最终的 html。另一个例子是向所有 js 文件添加“延迟”

标签: javascript node.js puppeteer


【解决方案1】:

打开页面后,立即设置page.setOfflineMode。这将阻止从预加载中加载该样式,从而停止 onload 事件!

代码:

await page.goto(url, {
    waitUntil: 'networkidle2',
});

await page.setOfflineMode(true);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多