将网址转换为截图(脚本)

7 投票
6 回答
32229 浏览
提问于 2025-04-16 04:41

这是一个互联网上页面的链接。我需要获取这个页面的截图(不管用哪个浏览器)。

我需要一个脚本(可以是PHP、Python,甚至是Django框架),这个脚本接收一个网址(字符串),然后输出一个截图文件(文件格式可以是gif、png或jpg)。

更新:

我需要动态创建一个页面,在这个页面上会显示与输入的网址相对应的截图。

6 个回答

1

这是一个使用谷歌页面速度的解决方案 - 已经测试过并且有效。

//SOLUTION 1

<?php
$link = "http://example.com";
$googlePagespeedData = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$link&screenshot=true");
$googlePagespeedData = json_decode($googlePagespeedData, true);
$screenshot = $googlePagespeedData['screenshot']['data'];
$screenshot = str_replace(array('_','-'),array('/','+'),$screenshot); 
$show_link = "<a href='$link'><img src=\"data:image/jpeg;base64,".$screenshot."\" /></a>";
echo $show_link;

//SOLUTION 2

$name = 'test';
$googlePagespeedData = file_get_contents("https://www.googleapis.com/pagespeedonline/v2/runPagespeed?url=$link&screenshot=true");
$googlePagespeedData = json_decode($googlePagespeedData, true);
$screenshot = base64_decode($googlePagespeedData['screenshot']['data']);
$data = str_replace('_','/',$googlePagespeedData['screenshot']['data']);
$data = str_replace('-','+',$data);
$decoded = base64_decode($data);
file_put_contents('myfolder/'.$name.'.jpg',$decoded);
$file_name = "$name.jpg";

/*
-- IMPORTANT INFORMATION -- READ BELOW --

Choose how to proceed!
1. Use the above to display screenshots of links = longer processing time for multiple links.
2. Save image to a file, reference the saved image = more disk space needed if multiple links.

Note the trade off between processing time and disk space, if you're on a shared hosting platform with a small disk space limit and envisage or already have a lot of users (forums beware) you may want to consider a bigger hosting plan or even a dedicated server.

*/
?>
2

PhantomJS 是一个更好的选择,可以从网址生成截图。下面的脚本展示了最简单的页面捕捉方法。它会加载Github的主页,然后把它保存为一张图片,命名为github.png。

var page = require('webpage').create();
page.open('http://github.com/', function() {
  page.render('github.png');
  phantom.exit();
});

要运行这个例子,先创建一个新的文件,叫做github.js。把上面的代码复制粘贴到github.js文件里。在命令行中,用PhantomJS运行这个新创建的脚本:

phantomjs github.js

有很多项目可以使用PhantomJS生成截图。Pageres可以生成可靠的截图,它是基于NodeJS和PhantomJS的。

6

为什么你需要写一个脚本,而不是直接使用其他网站提供的服务呢?
你可以看看我在用的这个:WebSnapr http://www.websnapr.com/
或者你可以去 http://www.google.ro/search?ie=UTF-8&q=website+thumbnail 搜索一下,看看有没有其他适合你需求的服务。

撰写回答