将 Nextjs Puppeteer Web Scraper 部署到 Vercel

问题描述 投票:0回答:1

我正在使用 Nextjs 和 Puppeteer 开发一个网络爬虫。一切都在本地主机上运行良好,但是一旦我部署,当我尝试访问 puppeteer 时,Vercel 部署的版本会出现 500 内部服务器错误。我查看了一些关于将无服务器木偶函数部署到 Vercel 的指南,以及一些建议的剧作家,但当我部署它时它仍然不起作用。以下是使用 puppeteer 的代码片段,这是 github 存储库:https://github.com/hellolol2016/EquilibriNews

import chromium from "chrome-aws-lambda";
import playwright from "playwright-core";

//FUNCTION TO RUN SEPARATE SCRAPE FUNCTIONS
async function scrapeInfiniteScrollItems(page, getNews, src) {
  let items = {};
  try {
    items = await page.evaluate(getNews);
  } catch (e) {
    console.log(e);
    console.log("bad source", src);
  }
  return items;
}

//FUNCTION TO SET UP BROWSER AND RETURN
export default async function handler(req, res) {
  const browser = await playwright.chromium.launch({
    args: chromium.args,
    executablePath:
      process.env.NODE_ENV !== "development"
        ? await chromium.executablePath
        : "/usr/bin/chromium",
    headless: process.env.NODE_ENV !== "development" ? chromium.headless : true,
  });
  const page = await browser.newPage();
  page.setJavaScriptEnabled(false);
  page.setViewport({ width: 1280, height: 3000 });

  await page.goto("https://www.foxnews.com/politics");
  let items = await scrapeInfiniteScrollItems(page, extractFox, "fox");
  //NOTE: I didn't include the extractFox function because it didnt use any puppeteer functions
  allArticles.fox = items;

  await browser.close();

  res.status(200).json(allArticles);
}

我尝试过一些关于此问题的其他文章,例如 https://puppeteer-screenshot-demo.vercel.app/?page=https://whitep4nth3r.com(这篇文章使用已弃用的 Node 版本)和 https ://ndo.dev/posts/link-screenshot(这就是我现在正在尝试的)。

我猜测解决方案是安装一个不同的库,其工作方式与 playwright / puppeteer / chrome-aws-lambda 类似,但在 Vercel 上部署为无服务器函数时仍然可以使用。

next.js puppeteer web-deployment vercel
1个回答
0
投票

我按照这篇文章并让它在 Vercel 上运行:

https://www.stefanjudis.com/blog/how-to-use-headless-chrome-in-serverless-functions/

我相信您的问题是 Chromium 太大,无法在无服务器功能中运行(50mb 限制)。

如果进行这些更改后仍然不起作用,请检查部署日志以查看无服务器功能是否达到 10 秒执行时间限制。

© www.soinside.com 2019 - 2024. All rights reserved.