gpt4 book ai didi

javascript - PHP 获取呈现的 Javascript 页面

转载 作者:行者123 更新时间:2023-12-04 02:06:47 25 4
gpt4 key购买 nike

我正在使用 AngularJS 开发应用程序。一切似乎都很好,直到我遇到了让我头疼的事情:SEO。

从许多引用资料中,我发现由 Google 机器人或 Bing 机器人抓取和编入索引的 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();
};
});

关于javascript - PHP 获取呈现的 Javascript 页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34129845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com