更新 2添加有关如何phantomjs
从 PHP使用的更多详细信息。
更新 1(澄清目标页面上的 javascript需要先运行后)
方法一:使用phantomjs(会执行javascript);
1.下载phantomjs并将可执行文件放在 PHP 二进制文件可以访问的路径中。
2.将以下2个文件放在同一目录下:
获取-website.php
<?php
$phantom_script= dirname(__FILE__). '/get-website.js';
$response = exec ('phantomjs ' . $phantom_script);
echo htmlspecialchars($response);
?>
获取-website.js
var webPage = require('webpage');
var page = webPage.create();
page.open('http://google.com/', function(status) {
console.log(page.content);
phantom.exit();
});
3.浏览到get-website.php
目标站点,http://google.com
执行内联javascript后返回内容。您也可以使用php /path/to/get-website.php
.
方法二:Ajax 和 PHP 一起使用(没有 phantomjs 所以不会运行 javascript);
/get-website.php
<?php
$html=file_get_contents('http://google.com');
echo $html;
?>
测试.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>on demo</title>
<style>
p {
color: red;
}
span {
color: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<button id='click_me'>Click me</button>
<span style="display:none;"></span>
<script>
$( "#click_me" ).click(function () {
$.get("/get-website.php", function(data) {
var json = {
html: JSON.stringify(data),
delay: 1
};
alert(json.html);
});
});
</script>
</body>
</html>