使得网络爬虫想要提取url中的图像

making web crawler want to extract the images in url

本文关键字:url 图像 提取 网络 爬虫      更新时间:2023-09-26

我想制作一个网络爬虫,从任何给定的url中提取标题、描述、关键字和图像。。提取后,我想保存在数据库中。。。我的代码不适用于图像。。。如有任何帮助,将不胜感激

    var $ = cheerio.load(html);
    var title = $('head title').text();
    var keywords = $('head meta[name=keywords]').attr('content');
    var desc = $('head meta[name=description]').attr('content');
    var links = $('a');
    var img= $('img').attr('content')
    console.log('Crawling "%s" | %s',title,this.url);
    async.map(links.map(function(){
        var href = $(this).attr('href');
        if(href && href != self._url && !(/^#('w)+/.test(href)) && !util.imageRegexp.test(href)){
         if(util.isExternal(href)){
         return 'INSERT INTO `queue` SET `id` = '''+util.id()+''', `url` = '+self.conn.escape(href)+', `from` = '+self.conn.escape(from);
          console.log("self.conn.escape" + self.conn.escape)
          }
          else {
          return 'INSERT INTO `queue` SET `id` = '''+util.id()+''', `url` = '+self.conn.escape(util.resolveRelativeURL(href,self._url))+', `from` = '+self.conn.escape(from);
          }
          }
          return false;
         }).filter(function(el){
        return !!el;
        })
        ,this.conn.query.bind(this.conn),function(e,result){
        if(e){
        console.log('Error writing queue.');
        console.log(e);
        }
        });
    this.conn.query('INSERT INTO `websites` SET ?',{
        id:util.id(),
        url:this.url,
        from:from,
        title:title,
        keywords:keywords || '',
        img:img || '',
        desc:desc || ''
    } 

如果通过$('img').attr('content'),您想将图像本身作为文件下载,这将不起作用,因为图像数据本身是HTML的独立资源,HTML只是标识图像的URL。因此,您需要根据图像的src属性值为其发出HTTPGET请求,并将其保存为文件。Node的核心http客户端库将工作,像requestsuperagent这样的npm模块也将工作。