pc.js 代碼
var http=require ("http");
var url="http://sports.sina.com.cn/nba/1.shtml";
http.get(url,(res)=>{
var html="";
res.on("data",function (chunk) {
html+=chunk;
});
res.on("end",function () {
console.log(html);
});
// 后臺(tái)返回的數(shù)據(jù),攜帶chunk數(shù)據(jù)
}).on("error",(e)=>{
console.log(e.message);
// 如果在訪問過程中有錯(cuò)誤,輸出錯(cuò)誤信息
});
爬取 新浪nba球明星
運(yùn)行:
node pc.js
只能爬出來 網(wǎng)頁的源代碼
此處需要一個(gè)npm 庫
cheerio
這是一個(gè)用正則來篩選信息的庫
npm install cheerio
pc1.js 代碼
var http=require ("http");
var cheerio=require("cheerio");
var url="http://sports.sina.com.cn/nba/1.shtml";
http.get(url,(res)=>{
var html="";
res.on("data",function (chunk) {
html+=chunk;
});
res.on("end",function () {
// console.log(html);
var $=cheerio.load(html);
console.log($("#right a").html());
$("#right a").each(function () {
console.log($(this).attr("href"));
});
});
// 后臺(tái)返回的數(shù)據(jù),攜帶chunk數(shù)據(jù)
}).on("error",(e)=>{
console.log(e.message);
// 如果在訪問過程中有錯(cuò)誤,輸出錯(cuò)誤信息
});
運(yùn)行:
node pc.js
能獲取到網(wǎng)頁的href標(biāo)簽內(nèi)容
pc2.js
var http=require ("http");
var cheerio=require("cheerio");
var fs=require("fs");
var url="http://sports.sina.com.cn/nba/1.shtml";
function httpGet(url,cb) {
var html="";
http.get(url,function (res) {
res.on("data",function (chunk) {
html+=chunk;
});
res.on("end",function () {
cb(html);
})
}).on("error",function (e) {
console.log(e.message);
});
return html;
}
httpGet(url,function (html) {
var $=cheerio.load(html);
$("#right a").each(function (index) {
var newUrl=$(this).attr("href");
httpGet(newUrl,function (body) {
var jq=cheerio.load(body);
fs.writeFile(`./news/${index}.txt`,jq("#artibody").text(),function (err) {
//用node.js 把獲取到的text放入一個(gè)news文件夾
if(err){
return console.log(err.message);
}
console.log("完成");
})
})
})
});
運(yùn)行:
node pc.js