使用JavaScript代码从Laravel控制器运行Puppeteer



我正在使用Puppeteer从laravel控制器启动浏览器,但是我不知道如何从控制器运行JavaScript代码

我的函数是这样的:

$script = <<<SCRIPT
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
await page.goto('http://my-url.com');
const button = await page.$('button#button');
await button.evaluate( button => button.click() );
await page.waitForTimeout(5000);
...
await browser.close();
})();
SCRIPT;
$process = new Process(['node', '-e', $script]);
$process->run();
$output = $process->getOutput();

当我尝试在节点shell中运行这部分代码时:

const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});     
const page = await browser.newPage();
await page.goto('http://my-url.com');
const button = await page.$('button#button');
await button.evaluate( button => button.click() );
await page.waitForTimeout(5000);
...
await browser.close();
})();

它工作得很好,我也可以看到一个浏览器正在打开。当我试着运行整个函数时,它不起作用。所以我认为我在控制器中运行JS代码的方式是错误的。

我为JavaScript代码script.js创建了一个新的js文件

// script.js
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({headless: false});     
const page = await browser.newPage();
await page.goto('http://my-url.com');
const button = await page.$('button#button');
await button.evaluate( button => button.click() );
await page.waitForTimeout(5000);
...
await browser.close();
})();

在控制器中我已经改变了:

$process = new Process(['path/to/node', 'path/to/script.js]);
$process->run();
if(!$process->isSuccessful()) {
throw new ProcessFailedException($process);
}
$output = $process->getOutput();
$errors = $process->getErrorOutput();

这对我来说很有用

最新更新