我正在使用AngularJS开发应用程序。一切似乎都很好,直到我遇到了一件让我头疼的事情:SEO。
从许多参考资料中,我发现谷歌机器人或必应机器人抓取和索引的AJAX内容"并不那么容易",因为抓取程序不呈现Javascript。
目前我需要一个使用PHP的解决方案。我使用PHP Slim Framework,所以我的主文件是index.PHP,它包含了一个函数来呼应我的index.html的内容。我的问题是:
是否可以用HTML制作渲染的Javascript的快照
我的策略是:
如果请求查询字符串包含_escaped_fragment_,则应用程序将生成一个快照,并将该快照作为响应而不是确切的文件
如有任何帮助,我们将不胜感激。谢谢
经过大量的搜索和研究,我终于通过将PHP与PhantomJS(2.0版)混合来解决我的问题。我使用PHP中的exec()函数来运行PhantomJS,并创建Javascript文件来获取目标URL的内容。以下是片段:
index.php
// Let's assume that you have a bin folder under your root folder directory which contains phantomjs.exe and content.js
$script = __DIR__ ."/bin/content.js";
$target = "http://www.kincir.com"; // target URL
$cmd = __DIR__."/bin/phantomjs.exe $script $target";
exec($cmd, $output);
return implode("", $output);
content.js
var webPage = require('webpage');
var system = require('system');
var page = webPage.create();
var url = system.args[1]; // This will get the second argument from $cmd, in this example, it will be the value of $target on index.php which is "http://www.kincir.com"
page.open(url, function (status) {
page.onLoadFinished = function () { // Make sure to return the content of the page once the page is finish loaded
var content = page.content;
console.log(content);
phantom.exit();
};
});
我最近发布了一个项目,该项目允许PHP访问浏览器。在这里获取:https://github.com/merlinthemagic/MTS.它还依赖于PhantomJS。
下载和设置后,您只需使用以下代码:
$myUrl = "http://www.example.com";
$windowObj = 'MTS'Factories::getDevices()->getLocalHost()->getBrowser('phantomjs')->getNewWindow($myUrl);
//now you can either retrive the DOM and parse it, like this:
$domData = $windowObj->getDom();
//this project also lets you manipulate the live page. Click, fill forms, submit etc.