PHP抓取网站快照图代码,轻松实现网页截图!
优采云 发布时间: 2023-03-20 11:29在互联网时代,很多人都需要对网站进行截图。然而,手动截图费时费力,不仅容易出错,而且效率低下。那么,有没有一种方法可以快速、准确地抓取网站快照图呢?答案是肯定的!本文将为大家介绍PHP抓取网站快照图代码,帮助大家轻松获取想要的网站截图。
1.什么是PHP抓取网站快照图代码?
PHP抓取网站快照图代码是一种利用PHP语言编写的程序,它可以自动化地获取指定网址的页面快照,并保存为图片格式。这个过程类似于我们在浏览器中手动进行截图的操作。
2. PHP抓取网站快照图代码的优点
相比于手动截图,使用PHP抓取网站快照图代码具有以下优点:
(1)准确性高:通过程序自动化抓取,避免了手动操作可能出现的失误。
(2)速度快:程序可以同时处理多个任务,在几秒钟内就能完成大量截图工作。
(3)可定制性强:用户可以根据自己的需求自定义抓取参数,如分辨率、保存格式等。
3. PHP抓取网站快照图代码的实现过程
下面将从以下8个方面逐步分析如何实现PHP抓取网站快照图代码。
(1)安装必要的扩展
在使用PHP进行抓取之前,需要先安装相关扩展。其中最重要的是php-gd扩展,它提供了在PHP中处理图片所需的函数库。此外还需要安装php-curl扩展和php-zip扩展。
(2)获取页面源码
在进行页面截图之前,需要先获取目标页面的源码。这一步可以使用curl函数来实现。以下是一个简单的curl函数示例:
php
$url ="https://www.ucaiyun.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$html = curl_exec($ch);
curl_close($ch);
这段代码会向指定URL发起请求,并返回响应内容。
(3)解析HTML并处理CSS
由于HTML页面中常常包含CSS样式表,因此需要将CSS样式表与HTML合并以便后续处理。这一步可以使用第三方库如PhantomJS、wkhtmltopdf等来实现。
(4)渲染页面
接下来需要将经过处理后的HTML和CSS渲染成图片。这一步可以使用imagecreatefromstring函数将HTML转换为GD库支持的Image对象,并使用imagepng或6f353691fb2f6a100c266d918031bd4a函数将Image对象保存为PNG或JPEG格式文件。
以下是一个简单的渲染函数示例:
php
function render_71860c77c6745379b0d44304d66b6a13($html,$css){
//合并HTML和CSS
$html_with_css = apply_css_to_html($html,$css);
//渲染HTML
$browser = new Browser();
$page =$browser->get('8d777f385d3dfec8815d20f7496026dc:text/html,'. urlencode($html_with_css));
$image_data =860c77c6745379b0d44304d66b6a13->screenshot();
//将Image对象保存为PNG文件
$filename = tempnam(sys_get_temp_dir(),'screenshot_').'.png';
file_put_contents($filename,$image_8d777f385d3dfec8815d20f7496026dc);
return $filename;
}
这段代码使用了一个名为Browser的第三方库来模拟浏览器环境,并将HTML渲染成Image对象并保存为PNG格式文件。
(5)设置请求头
在请求目标URL时需要设置合适的请求头以模拟浏览器行为。以下是一个示例请求头:
php
$headers = array(
'User-Agent:a9694ebf4d02ef427830292349e3172c/5.0(Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
'Accept: text/html,application/f1863f23897ea9c14d9606d667e84685+xml,application/xml;q=0.9,image/6a294358579240936bf4d66151e6e720,*/*;q=0.8',
'Accept-Encoding: gzip, deflate, sdch',
'Accept-Language: en-US,en;q=0.8',
);
(6)调整窗口大小
为了获得更好的截图效果,有时需要调整窗口大小以适应不同设备上的屏幕尺寸。以下是一个示例:
php
$viewport_width = 1024;
$viewport_height = 768;
<p>
$browser->setViewportSize(new \JonnyW\PhantomJs\Page\ViewportSize($viewport_width,$viewport_height));
</p>
这段代码将浏览器窗口大小设置为1024x768像素。
(7)错误处理
在进行页面截图时可能会出现各种错误,例如网络连接失败、目标URL不存在等等。因此需要对可能出现的错误做适当处理,并给出友好提示信息。
以下是一个简单的错误处理函数示例:
e3fa89b21e23f35dcba7f013d7d04720_cb5e100e5a9a3e7f6d1fd97512215282($message){
header('Content-Type: text/plain');
die("Error:".$message);
}
该函数会输出错误信息并停止程序运行。
(8)完整程序示例
最后给出一个完整的PHP抓取网站快照图代码示例:
```php
<?php
require_once 'vendor/autoload.php';
use JonnyW\PhantomJs\Client as PhantomClient;
use JonnyW\PhantomJs\DependencyInjection\ServiceContainer;
use JonnyW\PhantomJs\DependencyInjection\Compiler\RegisterEnginePass;
function capture_screenshot($url,$width,$height,$format){
//初始化PhantomJS客户端
$serviceContainer = ServiceContainer::getInstance();
$serviceContainer->setParameter('phantomjs.binary.path','/usr/local/bin/phantomjs');
//创建PhantomJS客户端实例
$client = PhantomClient::getInstance();
//设置视口大小
$client->getEngine()->setPath('/usr/local/bin/phantomjs');
//创建新页面并打开指定URL
$page =$client->getMessageFactory()->createPage();
//设置视口大小
if ($width &&$height){
if ($width > 2000 ||$height > 2000){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Invalid viewport size");
}
if ($width < 1280 ||(!$height &&!isset($_GET['full']))){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Viewport size too small");
}
if (!$height){
//如果未指定高度,则按宽高比自动计算高度
list($width_ratio,$height_ratio)= explode(':',$_GET['ratio']??'');
if (!$width_ratio ||!$height_ratio){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Invalid aspect ratio");
}
if ($width_ratio <= 0 ||$height_ratio <=0){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Invalid aspect ratio");
}
if ($width_ratio > 100 ||$height_ratio > 100){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Aspect ratio too large");
}
if (isset($_GET['full'])){
//全屏模式下高度设为-1表示自适应高度
860c77c6745379b0d44304d66b6a13->setViewportSize($width *($width_ratio /$height_ratio),-1);
} else {
//非全屏模式下按比例计算高度
list($_w,$_h)= getimagesizefromstring(file_get_contents('https://www.ucaiyun.com'));
if ($_w<= 0 ||$_h<=0){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Failed to get image size");
}
$_ratio =$_w/$_h;
if ($_ratio <=0){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Failed to calculate aspect ratio");
}
if ($_ratio <($width_ratio /$height_ratio)){
//图片宽度比屏幕小,则按图片宽高比计算高度
$_h= ceil($_w*($height_ratio /$width_ratio));
$_w+=$_w%2;
$_h+=$_h%2;
a1003be9f9734ad0f3f7e7670413a95b($_w> 2000 ||$_h> 2000){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Viewport size too large");
}
$_x_offset = ceil(($width -$_w)/2);
$_y_offset = ceil(($height -$_h)/2);
return sprintf('%dx%d+%d+%d',$_w,$_h,-$_x_offset,-$_y_offset);
} else {
//屏幕宽度比图片小,则按屏幕宽高比计算高度
$_h= ceil($width *($height_ratio /($width_ratio /$_ratio)));
a1003be9f9734ad0f3f7e7670413a95b($_h> 2000){
handle_cb5e100e5a9a3e7f6d1fd97512215282("Viewport size too large");
}
return sprintf('%dx%d+0+-%d', floor($_h*($_ratio /($width_ratio))),$_h, ceil(($height -$_h)/2));
}
}
} else {
//指定宽高直接设置视口大小即可
if ($format =='pdf'){
// PDF格式下需要设置较大视口以保证清晰度
//860c77c6745379b0d44304d66b6a13->setViewportSize(max(1024 *($width / max(1,$height)),1280), max(1024 *($height / max(1,$width)),960));
860c77c6745379b0d44304d66b6a13->setViewportSize(800,$height+100);
} else {
860c77c6745379b0d44304d66b6a13->setViewportSize(max(1280,$width), max(720,$height));
}
}
sleep(3); //延迟等待页面加载完成
//截屏并输出结果
switch ($format){
case 'pdf':
header('Content-Type: application/pdf');
echo pdf_capture_screenshot(860c77c6745379b0d44304d66b6a13);
break;
case 'jpeg':
case 'jpg':
header('Content-Type:979f739044b7abe846354309ed960a2d/jpeg');
echo jpeg_capture_screenshot(860c77c6745379b0d44304d66b6a13);
break;
default:
header('Content-Type:979f739044b7abe846354309ed960a2d/png');
echo png_capture_screenshot(860c77c6745379b0d44304d66b6a13);
break;
}
}
}
function pdf_capture_screenshot(JonnyW\PhantomJs\Http\ResponseInterface &$response)
{
$clientPath ='/usr/local/bin/phantomjs';
$tempFilename=tempnam(sys_get_temp_dir(),'phantomjs_').'.pdf';
file_put_contents('/tmp/response.log',$response->getContent());
$execCmd ="{$clientPath}--ssl-protocol=any --web-security=false ".'--load-images=true --local-to-remote-url-access=yes ./rasterize.js '.'"'.$response->getUrl().'"'.$tempFilename.' A4';
exec($execCmd);
return file_get_contents($tempFilename);
}
function jpeg_capture_screenshot(JonnyW\PhantomJs\Http\ResponseInterface &$response)
{
$clientPath ='/usr/local/bin/phantomjs';
$tempFilename=tempnam(sys_get_temp_dir(),'phantomjs_').'.jpeg';
file_put_contents('/tmp/response.log',$response->getContent());
$execCmd ="{$clientPath}--ssl-protocol=any --web-security=false ".'--load-images=true --local-to-remote-url-access=yes ./rasterize.js '.'"'.$response->getUrl().'"'.$tempFilename;
exec($execCmd);
return file_get_contents($tempFilename);
}
function png_capture_screenshot(JonnyW\PhantomJs\Http\ResponseInterface &$response)
{
$clientPath ='/usr/local/bin/phantomjs';
$tempFilename=tempnam(sys_get_temp_dir(),'phantomjs_').'.png';
file_put_contents('/tmp/response.log',$response->getContent());
$execCmd ="{$clientPath}--ssl-protocol=any --web-security=false ".'--load-images=true --local-to-remote-url-access=yes ./rasterize.js '.'"'.$response->getUrl().'"'.$tempFilename;
exec($execCmd);
return file_get_contents($tempFilename);
}
function handle_cb5e100e5a9a3e7f6d1fd97512215282($message)
{
header('Content-Type: text/plain');
die("Error:". htmlspecialchars_decode(strip_tags(trim(preg_replace('/[\s\r\n]+/','', preg_replace('/<[^>]*>/','', htmlspecialchars_decode(str_replace('&nbsp;','',。