我正在开发一个起始页,用户可以在其中使用公式向页面添加链接。他们可以添加名称、url、描述和上传图片。
我想自动化上传图片的过程,应该自动捕获图片。我的脚本应该截取用户在 url 中输入的网站。我知道我可以使用 html2canvas 截取 html 元素的屏幕截图.
方法一
我的第一个方法是将外部网站加载到 iframe,但这不起作用,因为某些页面对此有限制,例如甚至是 w3schools.com 上的 iframe 教程不起作用,我得到 Refused to display 'https://www.w3schools.com/' in a frame because it set 'X-Frame-Options' to 'sameorigin'。
HTML
<div id="capture" style="padding: 10px; color: black;">
<iframe src="https://www.w3schools.com"></iframe>
</div>
方法二
我的下一个方法是调用我的网络服务器,它加载目标网站并将 html 返回给客户端。这可行,但目标站点未正确呈现,例如图像未加载。 (见下面的截图)
HTML
<div id="capture" style="padding: 10px; color: black;"></div>
JS
var testURL = "http://www.google.de";
$.ajax({
url: "http://server/ajax.php",
method: "POST",
data: { url: testURL},
success: function(response) {
$("#capture").html(response);
console.log(response);
html2canvas(document.querySelector("#capture")).then(
canvas => {
document.body.appendChild(canvas);
}
);
}
});
PHP
if (!empty($_POST['url'])) {
$url = filter_input(INPUT_POST, "url");
}
$c = curl_init($url);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)
$html = curl_exec($c);
if (curl_error($c))
die(curl_error($c));
// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);
curl_close($c);
echo $html;
这有可能实现吗?
更新
我通过更改我的 ajax 设法加载了一些图片,但它们不是由 html2canvas 渲染的。??
var testURL = "http://www.google.de";
$.ajax({
url: "http://server/ajax.php",
method: "POST",
data: { url: testURL},
success: function(response) {
response = response.replace(/href="\//g, 'href="'+testURL +"/");
response = response.replace(/src="\//g, 'src="'+testURL +"/");
response = response.replace(/content="\//g, 'content="'+testURL +"/");
$("#capture").html(response);
console.log(response);
html2canvas(document.querySelector("#capture")).then(
canvas => {
document.body.appendChild(canvas);
}
);
}
});
结果
结果 Canvas
最佳答案
我喜欢 php,但对于屏幕截图,我发现使用 phantomjs 提供最好的结果
示例文件 screenshot.js
var page = require('webpage').create();
page.open('https://stackoverflow.com/', function() {
page.render('out.png');
phantom.exit();
});
然后从 shell 中:
phantomjs screenshot.js
或者来自 php:
exec("phantomjs screenshot.js &");
这里的目标是从 php 生成 js 文件。
在同一文件夹中生成名为 out.png 的文件。这是全高页面屏幕截图。
我们还可以从命令行使用 Firefox 进行良好的捕获。这无论如何都需要 X。
firefox -screenshot test.png http://www.google.de --window-size=1280,1000
关于javascript - 从外部网站截图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50216239/