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的server先翻牆把這個js下載下來,放到web上
6.修改代碼把includeJS指向自己搭的http server上
備注:
調試過程發現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)
注釋之后,會得到status值。