1

For example, I have this bunch of img tags, and I want to get all the src value. How can I do that? I tried Elements img = doc.select("img") then String imgSrc = img.attr("src"). The result is, I get only the first src. How can I get all the image src?

<img src="blah blah.jpg"></img>
<img src=".........jpg"></img>
...........
<img src="end.jpg></img>
Goo
  • 1,318
  • 1
  • 13
  • 31
homi3kh
  • 241
  • 1
  • 6
  • 17
  • Maybe [duplicate question](http://stackoverflow.com/questions/7465734/how-to-parse-for-image-src-using-jsoupmy). Look at it! – BendaThierry.com Sep 09 '12 at 10:37
  • it's not, the solution there only get the first src attribute like I tried, I want to get all the src that was selected. – homi3kh Sep 09 '12 at 10:42
  • ok, so you should look below, i've posted an answer to get all images. – BendaThierry.com Sep 09 '12 at 10:44
  • Tell what are you doing exactly: post some code, or if you don't want: write a JUnit test, and go in debug mode inside your parsing code, and look at your variables to see if it work or not and then you will be able to find where it blocks. You have some librairies like [jMock](http://www.jmock.org/) or [EasyMock](http://www.easymock.org/) or [Mockito](http://code.google.com/p/mockito/) which could help you to mock any dependencies not concerned by your test. I've just found [android-mock](http://code.google.com/p/android-mock/) – BendaThierry.com Sep 09 '12 at 13:23

2 Answers2

0

Maybe something like that:

Elements images = doc.select("img[src]");

print("\nImages: (%d)", images.size());
for (Element src : images) {
        print(
            " * %s: <%s> %sx%s (%s)", 
            src.tagName(), src.attr("abs:src"), src.attr("width"), src.attr("height"),
            trim(src.attr("alt"), 20)
        );
}

The JSoup Cookbook could help you for that!

trim part:

private static String trim(String s, int width) {
    if (s.length() > width)
        return s.substring(0, width-1) + ".";
    else
        return s;
}
BendaThierry.com
  • 2,080
  • 1
  • 15
  • 17
0

The Elements class is a collection. This means that you should be able to simply iterate over it and get the src value for every <img> element it contains.

Try this:

for(Element imgElement : img) {
    String imgSrc = imgElement("src");
}
Paul
  • 5,163
  • 3
  • 35
  • 43
  • `String imgSrc = imgElement("src");` has to be `String imgSrc = imgElement.attr("src");`, thats all. – ollo Sep 09 '12 at 20:35