2023-10-30 08:00:01

网站截图

有什么方法可以用PHP截图一个网站,然后保存到一个文件?


当前回答

我最后按照@boksiora的建议使用microweber/screen进行设置。 最初当尝试这里提到的链接时,我得到了什么:

Please download this script from here https://github.com/microweber/screen

我用的是Linux。所以如果你想运行它,你可以根据你的环境调整我的步进。 下面是我在shell上DOCUMENT_ROOT文件夹上做的步骤:

$ sudo wget https://github.com/microweber/screen/archive/master.zip
$ sudo unzip master.zip
$ sudo mv screen-master screen
$ sudo chmod +x screen/bin/phantomjs
$ sudo yum install fontconfig
$ sudo yum install freetype*
$ cd screen
$ sudo curl -sS https://getcomposer.org/installer | php
$ sudo php composer.phar update
$ cd ..
$ sudo chown -R apache screen
$ sudo chgrp -R www screen
$ sudo service httpd restart

将浏览器指向screen/demo/shot.php?url=google.com。当你看到屏幕截图时,你就完成了。更多高级设置的讨论可在这里和这里。

其他回答

有许多开源项目可以生成屏幕截图。例如PhantomJS, webkit2png等

这些项目的最大问题是,它们基于旧的浏览器技术,在渲染许多网站时存在问题,特别是在过去几个月/几年里使用webfonts、flexbox、svg和其他各种添加到HTML5和CSS规范的网站。

我尝试了一些第三方服务,大多数都是基于PhantomJS的,这意味着它们的截图质量也很差。生成网站截图的最好的第三方服务是urlbox.io。这是一项付费服务,但也有7天的免费试用,无需承诺任何付费计划。

这里是文档的链接,下面是让它在PHP中使用composer工作的简单步骤。

// 1 . Get the urlbox/screenshots composer package (on command line):
composer require urlbox/screenshots

// 2. Set up the composer package with Urlbox API credentials:
$urlbox = UrlboxRenderer::fromCredentials('API_KEY', 'API_SECRET');

// 3. Set your options (all options such as full page/full height screenshots, retina resolution, viewport dimensions, thumbnail width etc can be set here. See the docs for more.)
$options['url'] = 'example.com';

// 4. Generate the Urlbox url
$urlboxUrl = $urlbox->generateUrl($options);
// $urlboxUrl is now 'https://api.urlbox.io/v1/API_KEY/TOKEN/png?url=example.com'

// 5. Now stick it in an img tag, when the image is loaded in browser, the API call to urlbox will be triggered and a nice PNG screenshot will be generated!
<img src="$urlboxUrl" />

例如,这里是这个页面的全高截图:

https://api.urlbox.io/v1/ca482d7e-9417-4569-90fe-80f7c5e1c781/8f1666d1f4195b1cb84ffa5f992ee18992a2b35e/png?url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F757675%2Fwebsite-screenshots-using-php%2F43652083%2343652083&full_page=true

您可以使用简单的无头浏览器,如PhantomJS抓取页面。

你也可以在PHP中使用PhantomJS。

看看这个php脚本。看看这里https://github.com/microweber/screen

这里是API- http://screen.microweber.com/shot.php?url=https://stackoverflow.com/questions/757675/website-screenshots-using-php

如果你不想使用任何第三方工具,我遇到了一个简单的解决方案,那就是使用谷歌页面洞察api。

只需要调用它的api与params截图=true。

https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=https://stackoverflow.com/&key={your_api_key}&screenshot=true

对于移动站点视图传递&策略=移动参数,

https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=http://stackoverflow.com/&key={your_api_key}&screenshot=true&strategy=mobile

演示。

你可以使用剪贴画。

KWHTML已弃用,像旧浏览器一样显示页面。

Cutycapt保存网页的大多数图像格式(jpg,png..)下载它从你的突触,它比wkhtmltopdf工作得更好