使用JavaScript程式碼在Laravel控制器中執行Puppeteer操作
P粉098417223
P粉098417223 2023-08-28 09:40:29
0
1
478
<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學習者快速成長!