前因:項目需要采集N*NNNN組數(shù)據(jù)。但是該網(wǎng)頁是使用AJAX,POST請求獲取得到數(shù)據(jù)的。一般通常GET請求的就用火車頭一類的解決的,但是免費版本不能使用ajax獲取方式。又懶得寫Python(其實是環(huán)境沒裝)。只能靠萬能的JS來解決了。
適用人群:會寫點小JS,又懶得用Python,想二分鐘就搞定的。要是沒裝油猴子就十分鐘吧。。反正超快解決問題。
步驟:
1. 寫一段AJAX獲取數(shù)據(jù)。其實不用,頁面上就有請求的代碼,copy妥妥的
2. 使用油猴子(Tampermonkey)。一個用戶腳本管理器插件。安裝之后,可自動為您訪問的網(wǎng)站添加功能。比如百度網(wǎng)盤破解啦,視頻網(wǎng)站去廣告破解VIP啦都可以。這里就不贅述了。
直接把post獲取數(shù)據(jù)代碼放到油猴子里新建的腳本中
3. 使用FileSaver.js插件實現(xiàn)文件保存功能
油猴子支持引用外部js ?
?@require http://www.jq22.com/demo/FileSaver20161213/FileSaver.min.js
類似這樣的。。。
代碼中在得到返回數(shù)據(jù)后保存的代碼,類似
var BB = self.Blob;
// csv中列項用逗號分隔,行項用\n分隔,這里只是意思意思,實際一般是在post請求后得到返回的list數(shù)據(jù)后循環(huán)賦值。
var str=result.rows[i].timeHour + ","+result.rows[i].uuid+","+result.rows[i].customerId+","+result.rows[i].ip+ ","+result.rows[i].pageUrl +? "\n";
// 使用 Blob 和FileSaver保存CSV文件。
saveAs( new BB( ["\ufeff" + str], {type: 'text/csv;charset=utf8'} ) , "demo.csv" );
結(jié)果:基本上在油猴子上運行后,就能得到1個或者多個csv文件了。
誰說js不能導(dǎo)出文件的,嘿嘿嘿。
由于實際采集一個小小的栗子:
// @name? ? ? ? 獲得天天果園某個商品評論
// @namespace? ? http://tampermonkey.net/
// @version? ? ? 0.1
// @description? try to take over the world!
// @match? ? ? ? http://www.fruitday.com/prodetail/index/16987
// @grant? ? ? ? none
// @require http://www.jq22.com/demo/FileSaver20161213/FileSaver.min.js
// ==/UserScript==
/* jshint -W097 */
'use strict';
// Your code here...
var curr_page=0;
var str="";
var getComment = function(cpage){
$.post('http://www.fruitday.com/ajax/comment/pList',{id:16987,curr_page:cpage,type:""},
function(result)
{
result=JSON.parse(result);
var rlist=result.msg.list;
for(var i=0;i
var rlist=result.msg.list;
for(var i=0;i<=rlist.length;i++){
str+= rlist[i].id+ ","+ rlist[i].content+","+ rlist[i].time+ ","+ rlist[i].star +? "\n";
}
curr_page++;
if( curr_page==200){
$('body').html(str);
var BB = self.Blob;
saveAs( new BB( ["\ufeff" + str], {type: 'text/csv;charset=utf8'} ) , "天天果園評論demo.csv" );
}else{
getComment(curr_page);
}
}
)
};
$(function(){
$('body').html("正在進(jìn)行中....");
getComment(curr_page);
})
獲取的就是天天果園某個商品的評論,大概2000千吧。
到了excel就可以做點小小小小的分析了。