【问题标题】:RESTful Chromless implementationRESTful 无铬实现
【发布时间】:2017-10-22 19:29:04
【问题描述】:

我正在寻找一种使用无头 chrome 的方法,类似于 chromeless 所做的,但不是作为 nodejs 端点实现,而是允许将 html 内容作为有效负载的 restful 请求。

我想在通过 API Gateway 触发的 aws lambda 上运行此服务。有没有人有这个用例的经验?

【问题讨论】:

  • 欢迎来到 Stack Overflow。你会发现“有人有……吗?”这里通常不被视为good question。一个很好的问题,在这里,旨在理解和解决一个特定的编程问题。例如,在这里,我建议您需要尝试您想要完成的事情,并在您手头有代码以及无法按预期工作的最小、完整、可验证示例 (MCVE) 时提出问题。跨度>
  • Chromeless 看起来应该很容易适应您的用例,方法是从请求正文中提取 HTML,将其保存到文件或 S3 存储桶,然后以编程方式导航到它。

标签: google-chrome-devtools aws-lambda chromeless


【解决方案1】:

没有什么可以阻止您在用例中使用 Chromeless。 Chromeless 可以在 AWS Lambda 函数中使用。您可以接受来自 AWS API Gateway 的(RESTful)请求,然后使用它和 Chromeless 做一些事情。您可以将 @serverless-chrome/lambda 包与 Chromeless 结合使用,以在 Lambda 中运行无头 Chrome,以便 Chromeless 可以使用 Chrome。 Chromeless Proxy 以类似的方式工作。例如,您的 Lambda 函数的代码可能看起来像(这是我刚刚拼凑起来的未经测试的代码,但应该传达这个想法):

const launchChrome = require('@serverless-chrome/lambda')
const Chromeless = require('chromeless').Chromeless

module.exports.handler = function handler (event, context, callback) {
  const body = JSON.parse(event.body) // event.body coming from API Gateway
  const url = body.url
  const evaluateJs = body.evaluateJs

  launchChrome({
    flags: ['--window-size=1280x1696', '--hide-scrollbars'],
  })
    .then((chrome) => {
      // Chrome is now running on localhost:9222

      const chromeless = new Chromeless({
        launchChrome: false,
      })

      chromeless
        .goto(url)
        .wait('body')
        .evaluate(() => `
          // this will be executed in headless chrome
          ${evaluateJs}
        `)
        .then((result) => {
          chromeless
            .end()
            .then(chrome.kill) // https://github.com/adieuadieu/serverless-chrome/issues/41#issuecomment-317989508
            .then(() => {
              callback(null, {
                statusCode: 200,
                body: JSON.stringify({ result })
              })
            })
        })
        .catch(callback)
    })
    .catch((error) => {
      // Chrome didn't launch correctly
      callback(error)
    })
}

您可以在 Chromeless 问题跟踪器 here 上找到类似的主题。

披露:我是这些包的合作者/作者。

【讨论】:

    猜你喜欢
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多