使用JavaScript代码在Laravel控制器中执行Puppeteer操作
P粉098417223
P粉098417223 2023-08-28 09:40:29
0
1
480
<p>我正在使用Puppeteer从laravel控制器启动浏览器,但是我不知道如何从控制器运行JavaScript代码</p> <p>我的函数如下:</p> <pre class="brush:php;toolbar:false;">$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();</pre> <p>当我尝试在node shell中仅运行代码的这部分时:</p> <pre class="brush:php;toolbar:false;">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(); })();</pre> <p>它可以正常工作,我也可以看到打开了一个浏览器。当我尝试运行整个函数时,它不起作用。所以我认为我在控制器中运行JS代码的方式是错误的。</p>
P粉098417223
P粉098417223

全部回复(1)
P粉077701708

我为JavaScript代码创建了一个新的js文件 script.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();

这对我有用

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!