【问题标题】:How can I add html elements to the current page? puppeter/carlo如何将 html 元素添加到当前页面?木偶/卡罗
【发布时间】:2019-08-15 01:18:13
【问题描述】:

我正在尝试将html元素添加到当前页面

page.setContenet

但是当它到达时:

await page.setContent('<div><h1>hello world<h1></div>')

刷新页面,告别./index.html

有没有办法让这两个功能同时在同一个窗口中工作?

完整代码:

'use strict'

const path = require('path');
const carlo = require('carlo');
const puppeteer = require('puppeteer-core');
const { getExecutablePath } = require('./utils');

const run = async () => {
  const executablePath = await getExecutablePath({
  //  useLocalChromium: true
  });
  console.log('Executable path:', executablePath);
  launchPuppeteer({ executablePath });
}

run();

const launchPuppeteer = async launchOptions => {
  const test = path.join(__dirname, 'public')
  const final = test + '/index.html';
  const browser = await puppeteer.launch({
    headless: false,
    args: [`--app=${final}`, '--window-size=1280,1024'],
    ...launchOptions
  });

  const [page] = await browser.pages();

  await page.setViewport({width: 1280, height: 1024});
  await page.setContent('<div><h1>hello world<h1></div>')
}

【问题讨论】:

  • 请澄清一下,“这两个功能”是什么?这是什么意思? - “刷新页面并说再见”
  • 你在launchPuppeteer函数之前错过了awaitawait launchPuppeteer({ executablePath })
  • @Vaviloff 道歉。我想要做的是将 html 标签添加到我的 index.html 中。我使用await page.setContent ('&lt;div&gt; &lt;h1&gt; hello world &lt;h1&gt; &lt;/div&gt;'),但是当这部分代码到达时,它会更新浏览器并且我的 index.html 消失了。
  • @Yevhen 完成了,但它似乎继续做我上面描述的事情。

标签: puppeteer


【解决方案1】:

就用这个

await page.evaluate(()=>{
    document.body.innerHTML += '<div>Test</div>';
})

编辑:这个呢?

【讨论】:

  • 我有以下(node:6496) UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: main is not defined
  • 对不起,你应该把'main'而不是main
  • (node:6248) UnhandledPromiseRejectionWarning: Error: Evaluation failed: TypeError: Cannot read property 'appendChild' of null 我猜这是因为我没有这个名字的选择器......它会正确吗?
猜你喜欢
  • 2012-06-20
  • 2016-12-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-18
  • 2020-11-23
  • 1970-01-01
相关资源
最近更新 更多