// let mysql = require("mysql"); let axios = require('axios');//請求網址模塊 var request = require('request');//也是請求網址模塊,只不過下載圖片的函數比較簡單,所以用這個 let fs = require('fs');//用於操作文件流 const cheerio = require('cheerio') let url = "http://www.4399dmw.com/haizeiwang/renwu/" let headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/18.17763"} let i = 0; // 獲取每個人物的地址函數 async function get_onePice(){ let res = await axios.get(url,{ headers }); // cheerio加載res里面的數據 let $ = cheerio.load(res.data); $(".g_rolelist li a").each((i,element)=>{ href = "http://www.4399dmw.com"+ $(element).attr("href") // 根據地址,訪問任務詳情,抓取詳情信息 // console.log(href) // personInfo(href) let pattern = /http:\/\/.*?(gif|png|jpg)/gi; let image = $(element).html().match(pattern)[0]; i++;
//下載圖片 download_img(image,'./teacher/t'+i+'.jpg') }) } //獲取圖片個人信息 async function personInfo(href){ let res = await axios.get(href); let $ = cheerio.load(res.data); // 人物名稱,獲取元素文本 let user= $(".dm_title").text(); // user = user.substring(3,this.length) // 人物簡介,獲取元素的純頁面元素 let detail = $(".dm_content").html(); console.log(user) } // 異步執行函數,用於下載圖片,接收圖片地址,和文件命名方式兩個參數。 async function download_img(img_url, file_name){ await request(img_url).pipe(fs.createWriteStream(file_name)).on('close',function(){ console.log('pic saved!') }) } // 執行函數 get_onePice()