爲什麼要用JS抓取數據?
有的網站的安全性比較好,不能破解登錄的限制,使用JS可以繞開登錄的限制。實現方法:使用Google Chrome登錄抓取站的用戶賬號,在console運行js腳本即可。實例抓取淘寶賣家商品分類
var CAT = {
//[{id: '', name: '', data: [{id: '', name: '', data:[{id: '', name: ''}]},{}, ...]}, {} ...]
data: [],
url: function(){
return 'https://upload.taobao.com/auction/json/reload_cats.htm?t='+Math.random();
},
init: function(){
var url = CAT.url(),
post_data = 'path=all';
CAT.ajax(url, post_data, CAT.first_r);
},
first_r: function(data){
var rs = data[0]['data'],
first_l, first_d, i, j, second_id, second_d, func;
for(i=0;i<rs.length; i++){
//保存一級分類
first_d = rs[i]['data'];
first_l = [];
for(j=0; j<first_d.length; j++){
//保存二級分類同時查詢三級分類,並提供存儲數據的容器
second_id = first_d[j]['sid'];
second_d = {
'id': first_d[j]['sid'],
'name': first_d[j]['name'],
'spell': first_d[j]['spell'],
'data': []
};
first_l.push(second_d);
func = CAT.second_r(second_d['data']);
CAT.ajax(CAT.url(), 'path=next&sid='+second_id, func);
}
CAT.data.push({
'id': rs[i]['id'],
'name': rs[i]['name'],
'data': first_l
})
}
},
second_r: function(container){
return function(data){
if(data.length<1){
return
}
var rs = data[0]['data'],
i, j, here, third_d;
for(i=0; i<rs.length; i++){
third_d = rs[i]['data'];
for(j=0; j<third_d.length; j++){
here = third_d[j];
container.push({
'id': here['sid'],
'name': here['name'],
'spell': here['spell']
});
}
}
}
},
ajax: function(url, post_data, func){
var xhr = new XMLHttpRequest(),
result;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send(post_data);
xhr.onreadystatechange=function(){
if (xhr.readyState==4 && xhr.status==200){
result = JSON.parse(xhr.responseText);
func(result);
}else if(xhr.readyState==4 && (!xhr.status==200)){
console.log('Ajax Return Error!');
}
}
}
};
CAT.init();
//console.log(CAT.data);
JS代碼實現抓取網頁數據有一定的侷限性:數據源用ajax可以獲取,數據源是json格式。
http://www.test.com跨域抓取數據例子
var CAT = {
url: function () {
return 'https://upload.taobao.com/auction/json/reload_cats.htm?t=' + Math.random();
},
init: function () {
CAT.ajax(CAT.url(), 'path=next&sid=50024865', CAT.first_r);
},
first_r: function (data) {
if (data.length < 1) {
return
}
var rs = data[0]['data'],
i, j, here, third_d;
for (i = 0; i < rs.length; i++) {
third_d = rs[i]['data'];
for (j = 0; j < third_d.length; j++) {
here = third_d[j];
//配置Access-Control-Allow-Origin支持
CAT.ajax("http://www.test.com/taobao/data", 'id='+here['sid']+"&name="+here['name']+"&spell="+here['spell']+"&sid=50024865", CAT.mycallback_r);
}
}
},
mycallback_r: function (data) { //json
console.log(data);
},
ajax: function (url, post_data, func) {
var xhr = new XMLHttpRequest(),
result;
xhr.open('POST', url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(post_data);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
result = JSON.parse(xhr.responseText);
func(result);
} else if (xhr.readyState == 4 && (!xhr.status == 200)) {
console.log('Ajax Return Error!');
}
}
}
};
CAT.init();
原生js實現Ajax方法:
var Ajax = {
get: function (url, fn) {
// XMLHttpRequest對象用於在後臺與服務器交換數據
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onreadystatechange = function () {
// readyState == 4說明請求已完成
if (xhr.readyState == 4 && xhr.status == 200 || xhr.status == 304) {
// 從服務器獲得數據
fn.call(this, xhr.responseText);
}
};
xhr.send();
},
// datat應爲'a=a1&b=b1'這種字符串格式,在jq裏如果data爲對象會自動將對象轉成這種字符串格式
post: function (url, data, fn) {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
// 添加http頭,發送信息至服務器時內容編碼類型
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 304)) {
fn.call(this, xhr.responseText);
}
};
xhr.send(data);
}
}
註釋:
1. open(method, url, async) 方法需要三個參數:
method:發送請求所使用的方法(GET或POST);與POST相比,GET更簡單也更快,並且在大部分情況下都能用;然而,在以下情況中,請使用POST請求:
- 無法使用緩存文件(更新服務器上的文件或數據庫)
- 向服務器發送大量數據(POST 沒有數據量限制)
- 發送包含未知字符的用戶輸入時,POST 比 GET 更穩定也更可靠
url:規定服務器端腳本的 URL(該文件可以是任何類型的文件,比如 .txt 和 .xml,或者服務器腳本文件,比如 .asp 和 .php (在傳回響應之前,能夠在服務器上執行任務));
async:規定應當對請求進行異步(true)或同步(false)處理;true是在等待服務器響應時執行其他腳本,當響應就緒後對響應進行處理;false是等待服務器響應再執行。
2. send() 方法可將請求送往服務器。
3. onreadystatechange:存有處理服務器響應的函數,每當 readyState 改變時,onreadystatechange 函數就會被執行。
4. readyState:存有服務器響應的狀態信息。
- 0: 請求未初始化(代理被創建,但尚未調用 open() 方法)
- 1: 服務器連接已建立(
open
方法已經被調用) - 2: 請求已接收(
send
方法已經被調用,並且頭部和狀態已經可獲得) - 3: 請求處理中(下載中,
responseText
屬性已經包含部分數據) - 4: 請求已完成,且響應已就緒(下載操作已完成)
5. responseText:獲得字符串形式的響應數據。
6. setRequestHeader():POST傳數據時,用來添加 HTTP 頭,然後send(data),注意data格式;GET發送信息時直接加參數到url上就可以,比如url?a=a1&b=b1。