我使用白名单如下:
int
现在这非常接近我想做的事情,除了: 有div标签,其类具有“nav”或“ad”并填充页面 带有红色。我想保留div标签,但如果该类恰好出现“nav”或“ad”,则不会。
这让我想到了继承白名单...... RTFM http://jsoup.org/apidocs/org/jsoup/safety/Whitelist.html我明白了 addTag()和removeTag()(以某种方式removeTag()不可用,但这是另一个问题)。我真正想要做的是删除当且仅当标签的类包含sting中的某些值,例如'ad'或'nav'。 看起来充满希望的唯一方法是:
Document doc = Jsoup.parse(urls[0], 5000);
if (doc != null){
Whitelist wl = Whitelist.basicWithImages();
// wl.preserveRelativeLinks(false);
Cleaner cleaner = new Cleaner(wl);
cleanedDoc=cleaner.clean(doc);
if (cleanedDoc != null){
whiteListedHtml = cleanedDoc.html();
}
}
}catch(IOException e){
Log.d(TAG,"exception="+e.getMessage());
}
那么我怎样才能拿出这个字符串的类值进行测试?无论如何在没有子类化白名单的情况下进行此检查?现在我正在尝试这个:
protected boolean isSafeTag(String tag)
Test if the supplied tag is allowed by this whitelist
Parameters:
tag - test tag
Returns:
true if allowed
答案 0 :(得分:2)
无论如何在没有继承白名单的情况下进行此检查吗?
一种方法是删除不需要的div,然后清理生成的文档。
var result = new XmlDocument();
transform.Run(new DOMDestination(result));
String html = "<html><head></head><body><div class=\"ad\">Remove</div><p>Hello word</p><div>Don't remove</div></body></html>";
System.out.println("** BEFORE:\n" + html);
Document dirtyDoc = Jsoup.parse(html);
for (Element div : dirtyDoc.select("div.ad, div.nav")) {
div.remove();
}
Whitelist whitelist = Whitelist //
.basicWithImages() // your original choosen list
.addTags("div"); // Without this line, any div will be removed
Cleaner cleaner = new Cleaner(whitelist);
Document cleanedDoc = cleaner.clean(dirtyDoc);
System.out.println("\n** AFTER:\n" + cleanedDoc.html());
Jsoup 1.8.3