一、安装
Mac:首先安装chromedriver
brew tap homebrew/cask
brew cask install chromedriver
brew cask install chromium
brew cask reinstall chromium
引入包地址:https://github.com/chrome-php/headless-chromium-php
使用常见的错误:
Exception 'RuntimeException' with message 'Chrome process stopped before startup completed. Additional info: sh: chromium-browser: command not found'
使用说明:这个是由于你配置里面引入包的地址不对正确使用如下:
$browserFactory = new BrowserFactory("/Applications/Chromium.app/Contents/MacOS/chromium");
$browser = $browserFactory->createBrowser(['noSandbox' => $sandBox,
'headless' => true,
'connectionDelay' => 0.8,
'debugLogger'=> 'php://stdout']);
$page = $browser->createPage();
$page->navigate($url)->waitForReload();
$browser->close();
安装可以参考的地址:
https://github.com/cpbotha/homebrew-marmaduke-chromium
https://en.wikipedia.org/wiki/Chromium_(web_browser)#Differences_from_Google_Chrome
https://github.com/DomT4/homebrew-chromium
二、包的引入:
composer require chrome-php/chrome
https://packagist.org/packages/chrome-php/chrome
三、各使用方法
1、模拟浏览器访问
$browserFactory = new BrowserFactory("/Applications/Chromium.app/Contents/MacOS/chromium");
$browser = $browserFactory->createBrowser(['noSandbox' => $sandBox,
'headless' => true,
'connectionDelay' => 0.8,
'debugLogger'=> 'php://stdout']);
$page = $browser->createPage();
$page->navigate($url)->waitForReload();
$browser->close();
2、浏览器截图
$browserFactory = new BrowserFactory("/Applications/Chromium.app/Contents/MacOS/chromium");
$browser = $browserFactory->createBrowser(['noSandbox' => $sandBox,
'headless' => true,
'connectionDelay' => 0.8,
'debugLogger'=> 'php://stdout']);
$page = $browser->createPage();
$page->navigate($url)->waitForReload();
if ($sleepTime) { sleep(6); // 6s等待资源加载及渲染完成,一般异步处理的脚本需要等待 }
$x = 10;$y = 10;//离X、Y的边距
$width = 100;$height = 100;//截图的宽高
$clip = new Clip($x, $y, $width, $height);
$screenshot = $page->screenshot([
'clip' => $clip
]);
$screenshot->saveToFile('save-address.jpg');//地址保存的地址
问题:在liunx上有的截图可能会出现中文乱码,是因为系统缺少中文字体,可以安装yum install cjkuni-uming-fonts cjkuni-ukai-fonts 系统装字体
三、生成pdf文件,前面一样的后面加:
$options = [
'landscape' => true, // default to false
'printBackground' => true, // default to false
'displayHeaderFooter' => true, // default to false
'preferCSSPageSize' => true, // default to false ( reads parameters directly from @page )
'marginTop' => 0.0, // defaults to ~0.4 (must be float, value in inches)
'marginBottom' => 1.4, // defaults to ~0.4 (must be float, value in inches)
'marginLeft' => 5.0, // defaults to ~0.4 (must be float, value in inches)
'marginRight' => 1.0 // defaults to ~0.4 (must be float, value in inches)
];
$pdf = $page->pdf($options);
// 文件保存地址
$pdf->saveToFile($outputImgFullPath);
四、加载js:
$page->addScriptTag([
'url' => 'https://code.jquery.com/jquery-3.3.1.min.js'
])->waitForResponse();
$page->evaluate('$(".my.element").html()');//计算页面上线文给定字符串