java - 如何在不创建JSOUP文档的情况下处理图像标签

标签 java html jsoup

我有一个图像标签作为字符串。我需要解析标签并添加标签的类以及高度和宽度。为此,我使用了以下 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 对象一样实现

提前致谢。

最佳答案

据我所知,你不能。您可以使用Jsoup.parseBodyFragment(imgTag)反而。它还返回一个 Document 但一个空 shell,并确保解析的标签位于正文中。

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

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>

关于java - 如何在不创建JSOUP文档的情况下处理图像标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59175798/

相关文章:

JavaScript - Math.floor(Math.random()) - 重新定位 <img> 元素

java - 元素返回空字符串

java - 我想传递 Jsoup Connect.data() 方法的映射中的属性值

java - 获取页面的完整 html 源代码以制作网络爬虫

java - 侵入的确切含义是什么?是什么让 Spring 非侵入性的?

Java : Compare, 标记和解释 Java 中的 HTML 文本

html - Logo 和文本在同一行 - Bootstrap 导航栏

html - 使内部链接的 z-index 仅高于父容器

java - 获取给定日期范围内月份的开始日期和结束日期

Java Swing 按钮: setColor doesn't display the right color