运行 Azure Functions 编剧

Running Playwright in Azure Function

我正在尝试 运行 一个简单的 Azure 函数,它会根据浏览器中的可见内容进入页面并生成 PDF。

我使用 Linux 消费计划 (B1) 创建了一个 NodeJS 12 Azure 函数。我将 PLAYWRIGHT_BROWSERS_PATH 设置为 0

函数代码如下所示:

const { chromium } = require("playwright-chromium");

const baseUrl = "http://someurl";
const targetPage = "/action/";

module.exports = async function (context, req) {
    const browser = await chromium.launch();

    const page = await browser.newPage();
    console.log (baseUrl + targetPage + context.bindingData.id)
    await page.goto(baseUrl + targetPage + context.bindingData.id, { waitUntil: 'domcontentloaded' });
    
    await page.emulateMedia({ media: 'print' });
    const result = await page.pdf({ printBackground: true, format: 'letter' });
        
    context.res = {
      body: result,
      headers: { 'Content-Type': "application/pdf" }
    };   

    await page.close();
    await browser.close();
};

package.json

{
  "name": "",
  "version": "",
  "scripts": {
    "start": "func start",
    "test": "echo \"No tests yet...\""
  },
  "description": "",
  "devDependencies": {},
  "dependencies": {
    "playwright-chromium": "1.3.0"
  }
}

和function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get"
      ],
      "route": "route/{id}"
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

当我检查应用洞察时,我发现有以下错误:

Exception while executing function: Functions.PDF Result: Failure
Exception: Worker was unable to load function PDF: 'Error: Cannot find module 'playwright-chromium'
Require stack:
- /home/site/wwwroot/PDF/index.js
- /azure-functions-host/workers/node/worker-bundle.js
- /azure-functions-host/workers/node/dist/src/nodejsWorker.js'
Stack: Error: Cannot find module 'playwright-chromium'
Require stack:
- /home/site/wwwroot/PDF/index.js
- /azure-functions-host/workers/node/worker-bundle.js
- /azure-functions-host/workers/node/dist/src/nodejsWorker.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
    at Function.Module._load (internal/modules/cjs/loader.js:841:27)
    at Module.require (internal/modules/cjs/loader.js:1025:19)
    at require (internal/modules/cjs/helpers.js:72:18)
    at Object.<anonymous> (/home/site/wwwroot/PDF/index.js:1:22)
    at Module._compile (internal/modules/cjs/loader.js:1137:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1157:10)
    at Module.load (internal/modules/cjs/loader.js:985:32)
    at Function.Module._load (internal/modules/cjs/loader.js:878:14)
    at Module.require (internal/modules/cjs/loader.js:1025:19) 

虽然我没有忽略 node_modules 我得到了这个:

Exception while executing function: Functions.PDF Result: Failure
Exception: Error: browserType.launch: Failed to launch chromium because executable doesn't exist at /tmp/.cache/ms-playwright/chromium-792639/chrome-linux/chrome
Try re-installing playwright with "npm install playwright"
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
Stack: Error: browserType.launch: Failed to launch chromium because executable doesn't exist at /tmp/.cache/ms-playwright/chromium-792639/chrome-linux/chrome
Try re-installing playwright with "npm install playwright"
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
    at Chromium._launchServer (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:150:19)
    at async Chromium._innerLaunch (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:76:61)
    at async ProgressController.run (/home/site/wwwroot/node_modules/playwright-chromium/lib/progress.js:75:28)
    at async Chromium.launch (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:62:25)
    at async module.exports (/home/site/wwwroot/PDF/index.js:7:21) 

最后:

Exception while executing function: Functions.PDF Result: Failure
Exception: TimeoutError: browserType.launch: Timeout 30000ms exceeded.
=========================== logs ===========================
[browser] <launching> /home/site/wwwroot/node_modules/playwright-chromium/.local-browsers/chromium-792639/chrome-linux/chrome --no-sandbox --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=TranslateUI,BlinkGenPropertyTrees,ImprovedCookieControls,SameSiteByDefaultCookies --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --user-data-dir=/tmp/playwright_chromiumdev_profile-cPdg8P --remote-debugging-pipe --headless --hide-scrollbars --mute-audio --no-startup-window
[browser] <launched> pid=171
============================================================
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
Stack: TimeoutError: browserType.launch: Timeout 30000ms exceeded.
=========================== logs ===========================
[browser] <launching> /home/site/wwwroot/node_modules/playwright-chromium/.local-browsers/chromium-792639/chrome-linux/chrome --no-sandbox --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=TranslateUI,BlinkGenPropertyTrees,ImprovedCookieControls,SameSiteByDefaultCookies --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost --disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --user-data-dir=/tmp/playwright_chromiumdev_profile-cPdg8P --remote-debugging-pipe --headless --hide-scrollbars --mute-audio --no-startup-window
[browser] <launched> pid=171
============================================================
Note: use DEBUG=pw:api environment variable and rerun to capture Playwright logs.
    at ProgressController.run (/home/site/wwwroot/node_modules/playwright-chromium/lib/progress.js:71:30)
    at Object.runAbortableTask (/home/site/wwwroot/node_modules/playwright-chromium/lib/progress.js:24:23)
    at Chromium.launch (/home/site/wwwroot/node_modules/playwright-chromium/lib/server/browserType.js:62:42)
    at module.exports (/home/site/wwwroot/PDF/index.js:7:36)
    at WorkerChannel.invocationRequest (/azure-functions-host/workers/node/worker-bundle.js:18518:26)
    at ClientDuplexStream.<anonymous> (/azure-functions-host/workers/node/worker-bundle.js:18324:30)
    at ClientDuplexStream.emit (events.js:315:20)
    at addChunk (_stream_readable.js:295:12)
    at readableAddChunk (_stream_readable.js:271:9)
    at ClientDuplexStream.Readable.push (_stream_readable.js:212:10) 

我还认为,也许 playwright/puppeteer 只有在使用 Linux 消费计划(动态)时才能在 Azure Functions 上正常工作(当不使用 docker 部署时)?

我用你的例子玩了一会儿,我得到了同样的错误。这些是我发现使我的示例起作用的东西:

一定是Linux。我知道您提到您选择了 Linux 计划。但是我发现在 VS Code 中那部分是隐藏的,而在 Web 上默认是 Windows。这很重要,因为只有 Linux 计划在服务器上运行 npm install

确保您在服务器上构建。您可以在 VS 代码设置中找到此选项:

确保在发布之前设置环境变量 PLAYWRIGHT_BROWSERS_PATH