Search code examples
javahtmljsoupsrc

Get src of a class nested in a class with Jsoup


I am a beginner at jsoup, and I would like to get the src of the image in this code:

<div class="detail-info-cover"> 
<img class="detail-info-cover-img" src="http://fmcdn.mfcdn.net/store/manga/33647/cover.jpg? token=eab4a510fcd567ead4d0d902a967be55576be642&amp;ttl=1592125200&amp;v=1591085412" alt="Ghost Writer (MIKAGE Natsu)"> </div>

If you run it you will see the image I want to get.


Solution

  • Do it as follows:

    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.nodes.Element;
    
    public class Main {
        public static void main(String[] args){
            String html = "<div class=\"detail-info-cover\"> \n"
                    + "<img class=\"detail-info-cover-img\" src=\"http://fmcdn.mfcdn.net/store/manga/33647/cover.jpg? token=eab4a510fcd567ead4d0d902a967be55576be642&amp;ttl=1592125200&amp;v=1591085412\" alt=\"Ghost Writer (MIKAGE Natsu)\"> </div>";
            Document doc = Jsoup.parse(html);
            Element image = doc.select("img").first();
            String imageUrl = image.absUrl("src");
            System.out.println(imageUrl);
        }
    }
    

    Output:

    http://fmcdn.mfcdn.net/store/manga/33647/cover.jpg? token=eab4a510fcd567ead4d0d902a967be55576be642&ttl=1592125200&v=1591085412