下面是我需要解析的文本示例:
<P>The symbol <IMG id="pic1" height=15 src="images/itemx/image001.gif" width=18>indicates......</P>
我需要执行清理。因此,应用以下代码将删除src属性,因为它没有以有效的协议开始。如何配置Jsoup来拾取属性?如果可能的话,我想避免使用绝对url。
Jsoup.clean(content, Whitelist.basicWithImages());
只要在清理时指定了base URI
, jsoup cleaner将允许相对链接。这样就可以根据允许的协议来确认链路的协议。请注意,在您的示例中,您使用的是clean方法,没有基本URI,因此无法解析链接,因此必须删除该链接。
例如:
String clean = Jsoup.clean(html, "http://example.com/",
Whitelist.basicWithImages());
请注意,在当前版本中,任何相对链接将在清理后转换为绝对链接。我刚刚提交了一个更改(在下一个版本中可用),它将允许保留相对链接。
语法为:
String clean = Jsoup.clean(html, "http://example.com/",
Whitelist.basicWithImages().preserveRelativeLinks(true));
不幸的是,接受的答案对我不起作用,因为我必须支持多个域(包括多个开发环境和多个生产站点)。因此,我们确实需要相对url(不管它带来的危险)。我是这样做的:
// allow relative URLs. JSoup doesn't support that, so we use reflection
// removing the list of allowed protocols, which means all protocols are allowed
Field field = ReflectionUtils.findField(WHITELIST.getClass(), "protocols");
ReflectionUtils.makeAccessible(field);
ReflectionUtils.setField(field, WHITELIST, Maps.newHashMap());
(ReflectionUtils
是spring的一个类,它只是包装反射API抛出的检查异常)
这可能会有帮助:
whitelist.removeProtocols("a", "href", "ftp", "http", "https", "mailto");
whitelist.removeProtocols("img", "src", "http", "https");