如何选择不在链接元素内的所有图像?
document.select("a img"); //selects all images inside a link
document.select(":not(a) img"); //images not inside a link (does not work)
最佳答案
好的,所以这里的问题是 :not(a) img
只需要 <img>
周围的一个元素这不是 <a>
包含<img>
。例如<body>
匹配:not(a)
。所以你的选择器几乎匹配所有 <img>
标签。即使您将 HTML 字符串传递给 Jsoup.parse()
其中没有 <body>
或<html>
标签。 Jsoup 自动生成它。
假设我们有以下 HTML:
<html>
<body>
<a><div><img id="a-div-img"></div></a>
<a><img id="a-img"></a>
<img id="img">
</body>
</html>
如果您只想排除直接 <img>
<a>
中的 child 您可以使用:not(a) > img
作为选择器:
Elements images = document.select(":not(a) > img");
结果将是这样的:
<img id="a-div-img">
<img id="img">
问题在于它还打印了第一个 <img>
该示例实际上位于 <a>
内(#a-div-img
)。如果这足以满足您的需求,您可以采用此解决方案。
排除所有<a>
使用纯 CSS 不可能从选择中添加标签(至少我还没有找到解决方案)。但你可以删除所有 <a>
选择所有 <img>
之前从文档中标记标签:
document.select("a").remove();
Elements images = document.select("img");
结果将是这样的:
<img id="img">
如果您需要未经修改的原始文档,可以使用Document.clone()
之前:
Document tempDocument = document.clone();
tempDocument.select("a").remove();
Elements images = tempDocument.select("img");
使用它,原始文档永远不会被修改。
关于java - JSoup - 选择不在链接内的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56138153/