Search code examples
javascriptcasperjs

How to get img src of a class in casperjs


I have been battling with getting images src. What i needed is to get images with a specific class name and echo it on the console. I have tried different code method no luck. Please will appreciate your help. HTML code below.

<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 code below

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());
        });
    });
});

I want to get only the image of the class name: 'class="product-image-photo"'. If i used document.getElementByTagName('img'); it gets all images in the site, but if I use: document.getElementByClassName('product-image-photo'); Nothing returns. Will be happy to hear from you guys.


Solution

  • This would be simpler than your code.

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

    wrapping your get src code in casper.waitFor(...) would be more efficient.

    Updated code:

    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');
    });