最近研究如何能提高在openstack社區提交merge代碼的成功率,打算把其他人提的review都抓下來做點統計分析
review info頁的url pattern倒是很簡單:https://review.openstack.org/#/c/{id}/,可惜頁面是js生成的,wget搞不定
google了一下,測試框架+js引擎的方案的確比較全面,但對我來說無疑是大炮打蚊子,光一個pywebkit就折騰半天沒裝好。後來找到了phantomjs,發現非常適合我的需求,用法也極爲簡單:
1. 下載適合的壓縮包,下載頁: http://phantomjs.org/download.html
2. 以linux版爲例,解壓後有bin和example兩個目錄,其中bin/phantomjs可以直接執行(具體參數可通過bin/phantomjs --help獲取)
3. 在examples/下有個phantomwebintro.js,功能是下載http://www.phantomjs.org首頁中的intro信息,複製一份稍加修改就能可以了:
// Read the Phantom webpage '#intro' element text using jQuery and "includeJs"
var page = require('webpage').create();
page.onConsoleMessage = function(msg) {
console.log(msg);
};
page.open("https://review.openstack.org/#/c/38576/", 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("$(\"#gerrit_body\").text() -> " + $("#gerrit_body").text());
});
phantom.exit();
});
}
});
4. 用chrome打開需要抓取的頁面,通過審查元素可以發現需要抓取的主要內容都在div id="gerrit_body" 裏,對js做對應修改就可以直接用了:
bin/phantomjs test.js >test_result
5.如果想保留html標籤,可以把$("#gerrit_body").text()改成$("#gerrit_body").html()
更多的例子可以參考:
https://github.com/ariya/phantomjs/wiki/Examples