【问题标题】:How to process image tag without creating JSOUP Document如何在不创建 JSOUP 文档的情况下处理图像标签
【发布时间】:2020-03-29 05:49:38
【问题描述】:

我有一个图像标签作为字符串。我需要解析标签并为标签添加类和高度和宽度。为此,我使用了以下 JSOUP 代码。

String imgTag = "<img class=\"fit-picture\" src=\"/Downloads/grapefruit-slice-332-332.jpg\" alt=\"Grapefruit slice atop a pile of other slices\">";
Document doc = Jsoup.parse(imgTag);
Elements img = doc.select("img");
for (Element image:img) {
image.addClass("abc");
String styleStr = image.attr("style");
                    boolean setSize = true;
                    if(styleStr != null && !styleStr.isEmpty() && (styleStr.contains("width") || styleStr.contains("height"))){
                        setSize = false;
                    }
                    if(setSize) {
                    String w = image.attr("width");
                    String h = image.attr("height");

                    if(w == null || w.isEmpty()) {
                        image.attr("width",width+"");
                    }
                    if(h == null || h.isEmpty() ) {
                        image.attr("height",height+"");
                    }
                    }
}
String imgrep = doc.body().html();

输出:

<img class="fit-picture abc" src="/Downloads/grapefruit-slice-332-332.jpg" alt="Grapefruit slice atop a pile of other slices" width="332" height="332">

在上面的代码中,是否可以在不创建 JSOUP 文档的情况下实现输出?就像独立的 Tag 或 Element 对象实现一样

提前致谢。

【问题讨论】:

    标签: java html jsoup


    【解决方案1】:

    如果您需要将这些属性作为字符串添加,则不需要 JSOUP。

    你按照下面的方法做

    String imgTag = "<img class=\"fit-picture\" src=\"/Downloads/grapefruit-slice-332-332.jpg\" alt=\"Grapefruit slice atop a pile of other slices\" height=\""+height+"\" width=\""+ width +"\" >";
    

    【讨论】:

    • 我要解析很多图片标签。在这种情况下,有些标签已经有了类名,有些则没有。另外,我会检查是否有任何带有宽度和高度的样式属性,在这种情况下,我不会添加宽度和高度属性。
    • 您问题中的代码将 img 声明为字符串,这就是我建议此答案的原因。如果您已经拥有这些标签(即不是您在代码中构建的),那么您必须以某种方式解析它 JSOUP 是其中一种方法。
    • 在Jsoup中,本身有没有办法创建Standalone Tag或者Element来实现输出
    【解决方案2】:

    据我所知,你不能。您可以改用Jsoup.parseBodyFragment(imgTag)。它还返回一个Document,但它是一个空壳,并确保解析后的标签在正文中。

    您也可以像这样跳过文档创建:

    final List<Node> nodes = Parser.parseFragment(imgTag, null, "");
    

    但结果仍然是具有以下 HTML 的一个节点的列表:

    <html>
     <head></head>
     <body>
      <img class="fit-picture" src="/Downloads/grapefruit-slice-332-332.jpg" alt="Grapefruit slice atop a pile of other slices">
     </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 2014-12-30
      • 1970-01-01
      • 2016-10-25
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 2015-12-28
      • 2014-03-15
      相关资源
      最近更新 更多