2016-12-30 30 views
2

我一直在爭取獲取圖像src。我需要的是獲取具有特定類名稱的圖像並在控制檯上回顯它。我曾嘗試過不同的代碼方法,但沒有運氣請感謝您的幫助。下面的HTML代碼。下面如何在casperjs中獲得一個類的img src

casper.then(function getImages(){ 
    links = this.evaluate(function(){ 
     var links = document.getElementsByClassName('product-image-photo'); 
     links = Array.prototype.map.call(links,function(link){ 
      return link.getAttribute('src'); 
     }); 
     return links; 
    }); 
}); 

casper.then(function(){ 
    this.echo(this.getCurrentUrl()); 
    this.each(links,function(self,link){ 
     self.thenOpen(link,function(src){ 
      this.echo(this.getCurrentUrl()); 
     }); 
    }); 
}); 

我想要得到的類名的只有圖像

<a href="http://www.yudala.com/tecno-w5-1gb-16gb-grey.html" class="product photo product-item-photo" tabindex="-1"> 
    <span class="product-image-container em-alt-hover" style="width:205px;"> 
     <span class="product-image-wrapper" style="padding-bottom: 100%;"> 
      <img class="product-image-photo" src="http://www.yudala.com/pub/media/catalog/product/cache/1/thumbnail/280x280/beff4985b56e3afdbeabfc89641a4582/t/e/tecno_w5.jpg" alt="Tecno W5 | 1GB, 16GB | Grey + Free Alcatel 1050D Phone" width="205" height="205"> 
     </span> 
    </span> 
</a> 

JS代碼:「類=‘產品圖像照片’」。如果我使用document.getElementByTagName('img');它獲取網站中的所有圖像,但是如果我使用:document.getElementByClassName('product-image-photo');沒有回報。很高興聽到你們的消息。

+0

更新的答案,沒有測試它,但它應該工作在邏輯 – Garfield

+0

玫瑰,東西肯定與document.getElementsByClassName返回。它返回一個類似數組的對象。你可以嘗試console.log(document.getElementsByClassName('product-image-photo')); ?檢查您的瀏覽器控制檯。它是否會返回您的圖像? –

回答

0

這會比你的代碼更簡單。

casper.evaluate(function(){ 
    if(document.querySelector('.product-image-photo')){ 
     return document.querySelector('.product-image-photo').src; 
    } 
}); 

將您的src代碼包裝到casper.waitFor(...)會更高效。

更新代碼:

casper.waitForSelector('ol.products li.product-item', function(){ 
    var links = this.evaluate(function(){ 
     var imgs = document.querySelectorAll('ol.products li.product-item .product-image-wrapper img'); 
     var links = []; 
     for(var i=0; i<imgs.length; i++){ 
      links.push(imgs[i].src); 
     } 
     return links; 
    }); 

    this.then(function(){ 
     this.each(links, function(){ 
      // further code here 
     }); 
    }); 
}, function(){ 
    this.echo('No el. found'); 
}); 
+0

已經完成了你的建議,但仍然沒有工作....沒有得到任何結果d控制檯 –

+0

你可以發佈鏈接從哪裏你刮? – Garfield

+0

好的,謝謝,沒有測試過,但這裏是我想要廢棄的網站鏈接:www.yudala.com –

相關問題