简体   繁体   English

如何从jsoup中的ap标签中选择图像?

[英]How to select image from a p tag in jsoup?

I have ap tag like this 我有这样的ap标签

<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"); 我可以通过Elements pTag = document.select("p");获得p标签Elements pTag = document.select("p"); I have two problems: 我有两个问题:

  1. I want to get the image from the above p tag in jsoup. 我想从jsoup中的上述p标签获取图像。

  2. How would I know whether ap tag has an image or not? 我怎么知道ap标签是否有图像?

How can I achieve this? 我该如何实现? Please help me. 请帮我。

You could select the image tag with select("img") again. 您可以再次使用select(“ img”)选择图像标签。 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"). 如果这样做,可以检查是否元素为空以及是否要获取src属性,然后使用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" ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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