我正在尝试使用Jsoup提取img。它对于文件名中没有任何空格的图像效果很好,但是如果存在空格,则仅提取第一部分。
我尝试了以下。
String result = Jsoup.clean(content,"https://rally1.rallydev.com/", Whitelist.relaxed().preserveRelativeLinks(true), new Document.OutputSettings().prettyPrint(false));
Document doc = Jsoup.parse(result);
Elements images = doc.select("img");
例如HTML内容
Description:<div>some text content<br /></div>
<div><img src=/slm/attachment/43647556403/My file with space.png /></div>
<div><img src=/slm/attachment/43648152373/my_file_without_space.png/></div>
result
内容是:
Description:Some text content<br> <img src="/slm/attachment/43647556403/My"><img src="/slm/attachment/43648152373/my_file_without_space.png/">
在“结果”中,文件名中带有空格的图像只有第一部分“我的”。它忽略空格后的内容。
如果文件名包含空格,如何提取?
在Jsoup中无法轻松解决该问题,因为src
带有空格的示例的属性值实际上被正确标识为only My
。的file
,with
并且space.png
部分是在这个例子中没有值也属性。当然,您可以使用JSoup将src属性后面的属性键连接到其值。例如这样:
String test =""
+ "<div><img src=/slm/attachment/43647556403/My file with space.png /></div>"
+ "<div><img src=/slm/attachment/43647556403/My file with space.png name=whatever/></div>"
+ "<div><img src=/slm/attachment/43647556403/This breaks it.png name=whatever/></div>"
+ "<div><img src=\"/slm/attachment/43647556403/This works.png\" name=whatever/></div>"
+ "<div><img src=/slm/attachment/43648152373/my_file_without_space.png/></div>";
Document doc = Jsoup.parse(test);
Elements imgs = doc.select("img");
for (Element img : imgs){
Attribute src = null;
StringBuffer newSrcVal = new StringBuffer();
List<String> toRemove = new ArrayList<>();
for (Attribute a : img.attributes()){
if (a.getKey().equals("src")){
newSrcVal.append(a.getValue());
src = a;
}
else if (newSrcVal.length()>0){
//we already found the scr tag
if (a.getValue().isEmpty()){
newSrcVal.append(" ").append(a.getKey());
toRemove.add(a.getKey());
}
else{
//the empty attributes, i.e. file name parts are over
break;
}
}
}
for (String toRemAttr : toRemove){
img.removeAttr(toRemAttr);
}
src.setValue(newSrcVal.toString());
}
System.out.println(doc);
该算法遍历所有img元素,并在每个img内遍历其属性。找到src
属性后,将其保留以供参考,并开始填充newSrcBuf
StringBuffer。后面的所有无值属性都将添加到,newSrcBuf
直到找到另一个具有值的属性或没有其他属性为止。最后,用的内容重置scr属性值,newSrcBuf
并从DOM中删除以前的空属性。
请注意,当文件名包含两个或多个连续空格时,此功能将无效。JSoup会丢弃属性之间的那些空格,因此您无法在解析后将它们找回来。如果需要,则需要在解析之前操纵输入html。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句