首先需要導(dǎo)入node.js
-node.js 下載地址:https://nodejs.org/en/
shell
npm install cnpm --save 導(dǎo)入cnpm安裝市場 比node.js自帶的npm市場下載速度要快
cnpm install nightmare --save 導(dǎo)入nightmare 模塊 實現(xiàn) 模擬瀏覽器窗口訪問
cnpm install cheerio --save 導(dǎo)入cheerio 模塊 實現(xiàn) 訪問 獲取到的腳本數(shù)據(jù)
//導(dǎo)入fs 模塊
const fs = require("fs")
//導(dǎo)入 安裝的cheerio 模塊
const cheerio = require("cheerio")
//導(dǎo)入 nightmare 模塊
const Nightmare = require('nightmare')
//調(diào)出 nightmare 自帶的控制臺和模擬網(wǎng)頁窗口
const nightmare = Nightmare({
show: true,
openDevTools: {
mode: 'detach'
}
})
//需要爬的地址 這里是網(wǎng)易云的示例頁面
let home_url = "https://music.163.com/#/discover/artist/cat?id=1002"
nightmare
//開始訪問鏈接
.goto(home_url)
//利用代碼模擬點擊 nightmare自帶的click方法 里面填selector
//.m-cvrlst li:nth-child(16) a 選擇我們需要的a標簽里的內(nèi)容
.click(".m-cvrlst li:nth-child(16) a", () => {
console.log("點擊完了......")
//設(shè)置延時定時器 限制訪問速度,兩秒后開始執(zhí)行
setTimeout(() => {
console.log("新界面....")
//這里訪問點擊后獲取的新頁面數(shù)據(jù)
nightmare.goto("https://music.163.com/#/artist?id=9548")
//evaluate 評價 評估 這里返回的數(shù)據(jù) 會傳到下面then 的data里
.evaluate(() => {
return document.querySelector(".g-iframe").contentWindow.document.querySelector("body").innerHTML
})
.then((data) => {
console.log("開始查詢.,,....")
//因為抓取的innerHTML 里是利用腳本拼接的方式拼接到body里
//所以這里用到cheerio 模塊 來執(zhí)行 獲取到的數(shù)據(jù)
let $ = cheerio.load(data)
//定義一個 空數(shù)組 來保存 獲取到的歌曲信息
let songs = []
$(".m-table tr .txt a").each((i, item) => {
let song_id = $(item).attr("href")
let song_name = $(item).find("b").attr("title")
let tmp_dic = {
"song_id": song_id,
"song_name": song_name
}
songs.push(tmp_dic)
})
//將數(shù)組里的數(shù)據(jù) 通過JSON方式 轉(zhuǎn)換字符串
let songs_string = JSON.stringify(songs)
let file_name = "./test/" + $(".sname-max").text() + ".json"
fs.writeFile(file_name, songs_string, () => {
})
})
}, 2000);
})
.then(() => {
})
//捕獲錯誤
.catch((err) => {
console.log("訪問錯誤", err)
})