nodejs相關(guān)模塊
獲取網(wǎng)頁內(nèi)容(http\request\superagent等)
篩選網(wǎng)頁信息(cheerio)
輸出或存儲信息(console\fs\mongodb\mysql等)
1磁玉、使用 request 模塊來獲取網(wǎng)頁內(nèi)容
var request = require('request');
// 通過 GET 請求來讀取 http://cnodejs.org/ 的內(nèi)容
request('http://cnodejs.org/', function (error, response, body) {
if (!error && response.statusCode == 200) {
// 輸出網(wǎng)頁內(nèi)容
console.log(body);
}
});
如果是其他的請求方法,或者需要指定請求頭等信息扼仲,可以在第一個參數(shù)中傳入一個對象來 指定液南,比如:
var request = require('request');
request({
url: 'http://cnodejs.org/', // 請求的URL
method: 'GET', // 請求方法
headers: { // 指定請求頭
'Accept-Language': 'zh-CN,zh;q=0.8', // 指定 Accept-Language
'Cookie': '__utma=4454.11221.455353.21.143;' // 指定 Cookie
}
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // 輸出網(wǎng)頁內(nèi)容
}
});
2、使用 cheerio 模塊來提取網(wǎng)頁中的數(shù)據(jù)
cheerio 是一個 jQuery Core 的子集,其實現(xiàn)了 jQuery Core 中瀏覽器無關(guān)的 DOM 操作 API祠锣,以下是一個簡單的示例:
var cheerio = require('cheerio');
// 通過 load 方法把 HTML 代碼轉(zhuǎn)換成一個 jQuery 對象
var $ = cheerio.load('<h2 class="title">Hello world</h2>');
// 可以使用與 jQuery 一樣的語法來操作
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
console.log($.html());
// 將輸出 <h2 class="title welcome">Hello there!</h2>
3、使用 mysql 模塊來將數(shù)據(jù)儲存到數(shù)據(jù)庫
mysql 模塊內(nèi)置了連接池機制咽安,以下是一個簡單的使用示例:
var mysql = require('mysql');
// 創(chuàng)建數(shù)據(jù)庫連接池
var pool = mysql.createPool({
host: 'localhost', // 數(shù)據(jù)庫地址
user: 'root', // 數(shù)據(jù)庫用戶
password: '', // 對應(yīng)的密碼
database: 'example', // 數(shù)據(jù)庫名稱
connectionLimit: 10 // 最大連接數(shù)伴网,默認為10
});
// 在使用 SQL 查詢前,需要調(diào)用 pool.getConnection() 來取得一個連接
pool.getConnection(function(err, connection) {
if (err) throw err;
// connection 即為當(dāng)前一個可用的數(shù)據(jù)庫連接
});
參考文檔
jquery選擇器總結(jié) https://www.cnblogs.com/xiaxuexiaoab/p/7091527.html
nodejs爬蟲 https://www.cnblogs.com/xiaxuexiaoab/p/7124956.html