js 抓取网页内容(1.安装phantomjs网上有很多。执行官网上的示例代码3.执行状态)
优采云 发布时间: 2021-10-03 03:05js 抓取网页内容(1.安装phantomjs网上有很多。执行官网上的示例代码3.执行状态)
1.安装phantomjs
网上有很多
2.在官方网站上执行示例代码
// Read the Phantom webpage '#intro' element text using jQuery and "includeJs"
"use strict";
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open("http://phantomjs.org/", function(status) {
if (status === "success") {
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
page.evaluate(function() {
console.log("$(\".explanation\").text() -> " + $(".explanation").text());
});
phantom.exit(0);
});
} else {
phantom.exit(1);
}
});
3.执行状态一直卡在那里,不报告错误,不允许退出
要查看程序的内部执行状态,请添加操作日志
page.onResourceRequested = function (req) {
console.log('requested: ' + JSON.stringify(req, undefined, 4));
};
page.onResourceReceived = function (res) {
console.log('received: ' + JSON.stringify(res, undefined, 4));
};
4.发现该程序被困在JS请求中
http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js
5.只需在您自己的服务器上使用Python的simplehttpserver构建一个HTTP服务器。首先通过FQ下载JS并将其放到web上
6.修改代码并将includejs指向您自己的HTTP服务器
备注:
在调试期间,phantomjs中发现的另一个问题是page.open是异步执行的,如下代码所示:
var webPage = require('webpage');
var page = webPage.create();
page.open('http://www.baidu.com/', function(status) {
console.log('Status: ' + status);
// Do other things here...
});
phantom.exit(1)
完成执行后,打印返回值echo$?,将得到1
你把
phantom.exit(1)
注释之后,您将获得状态值