简体   繁体   中英

How to select image from a p tag in jsoup?

I have ap tag like this

<p><img class="aligncenter size-full wp-image-610" src="https://muslimmemo.com/wp-content/uploads/2015/08/al-rundi-fall-seville-poem-arabic.png" alt="al-rundi-fall-seville-poem-arabic" width="591" height="606" /></p>

I can get the p tag by Elements pTag = document.select("p"); I have two problems:

  1. I want to get the image from the above p tag in jsoup.

  2. How would I know whether ap tag has an image or not?

How can I achieve this? Please help me.

You could select the image tag with select("img") again. If you do so you could check, if the Elements are empty or not and if you want to get the src attribute then use img.attr("src"). Could look like that:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

public class JSoupAnswer {

    public static void main(String[] args) {

        String p = "<p><img class=\"aligncenter size-full wp-image-610\" src=\"https://muslimmemo.com/wp-content/uploads/2015/08/al-rundi-fall-seville-poem-arabic.png\" alt=\"al-rundi-fall-seville-poem-arabic\" width=\"591\" height=\"606\" /></p>";
        Document doc = Jsoup.parse(p);
        Elements img = doc.select("p").select("img");
        if (img.size() > 0)
            System.out.println(img);
    }

}

Output:

<img class="aligncenter size-full wp-image-610" src="https://muslimmemo.com/wp-content/uploads/2015/08/al-rundi-fall-seville-poem-arabic.png" ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM