user3256010
user3256010

Reputation: 7

Extract Image source from nested div and a tag in JSOUP

 <div class='ym-gbox adds-header'> 
     <a href='javascript:(void);' >
         <a href="http://epaper.thedailystar.net/" target="_blank">
         <img src="http://epaper.thedailystar.net/images/edailystar.png" alt="edailystar" style="float: left; width: 100px; margin-top: 15px;">
         </a>
         <a href="http://www.banglalink.com.bd/celebrating10years" target="_blank" style="display:block;float: right;">
         <img width="490" height="60" src="http://bd.thedailystar.net/upload/ads/2015/02/12/BD-News_490x60.gif" alt="banglalink" >
         </a>
     </a>
</div>

This is the html portion. From here I want to extract the image source of image tag with source address src="http://epaper.thedailystar.net/images/edailystar.png" using jsoup in android. But I failed. If anyone give the answer I will be thankful to him.

Here is my code

Document document = Jsoup.connect(url).get();
Elements img = document.select("div[class=ym-gbox adds-header]").first().select("a[href=http://epaper.thedailystar.net/] > img[src]");
String imgSrc = img.attr("src");

Upvotes: 0

Views: 1584

Answers (2)

Yevgen
Yevgen

Reputation: 1667

You have to iterate through elements to choose the element that suits your needs. Like so:

Elements elements = document.getElementsByTag("img");

for (Element element : elements) {
    if (element.attr("src").endsWith("png")) {
        System.out.println(element.attr("src"));
    }
}

Upvotes: 2

Yuva Raj
Yuva Raj

Reputation: 3881

Since you didn't mention url, i assume url is http://epaper.thedailystar.net/index.php

Document doc = Jsoup.connect("http://epaper.thedailystar.net/index.php").timeout(10*1000).get();
Elements div = doc.select("div.logo");
Elements get = div.select("img");
System.out.println(get.attr("abs:src"));

Output :

http://epaper.thedailystar.net/images/edailystar.png

Upvotes: 3

Related Questions