Node爬虫实践

爬虫的原理很好理解,就是在服务端请求另一个服务器的资源,前端有跨域问题,而服务端没有,这是天然优势。掌握node的前端可以为所欲为了。t_0003.gif

1 首先,根据请求资源的协议选择合适的模块,比如csdn是https协议,就用https的方法取请求,之前没有注意到这个问题。

var https = require('https');

2 用get方法请求需要抓去内容的网页地址,试过用request方法,没有反应。

 https.get('https://www.xxx.net',function(res){
        ......
 })

3 用cheerio模块查找dom元素,抓取需要的内容。cheerio是服务端的dom操作工具,以jquery为内核。

var cheerio = require('cheerio');
     res.on('data', (chunk) => {
        const $ = cheerio.load(chunk);
        let content=$('.company_list');
     })

4 把图片的绝对地址改成本地路径,前端页面无法直接访问跨域受保护图片。

let imgsrc=[];
content.find('img').each((index,e)=>{
    
    var originsrc=e.attribs.src;
    e.attribs.src ='/images/'+e.attribs.src.split('?')[0].split('/').pop();
    imgsrc.push(originsrc);

})

5 最后一步,也是最重要的一步:把图片保存在本地文件夹。试过fs.readFile 和fs.writeFile,保存下来的图片受损打不开;试过直接get请求,返回的图片都是0字节。正确的方法是用request方法,至于为什么?我也不清楚啊。可能是binary二进制的优势,毕竟再怎么伪装,所有数据本质还是二进制吧。


var request = require('request');
imgsrc.forEach(item=>{

    var filename = item.split('?')[0].split('/').pop();

    request({ url: item, encoding: null }, (err, response, body) => { 
        fs.writeFileSync('./public/images/'+filename, body, { encoding: 'binary' });
    })

})

到此为止,爬虫的功能就结束了。w_0005.gif


猜你喜欢

转载自blog.51cto.com/14430893/2417059