首页 > 解决方案 > JSoup - 选择不在链接内的图像

问题描述

如何选择不在链接元素内的所有图像?

document.select("a img"); //selects all images inside a link
document.select(":not(a) img"); //images not inside a link (does not work)

标签: javahtmlcss-selectorsjsoup

解决方案


好的,所以这里的问题是只:not(a) img需要一个<img><a>包含<img>. 例如<body>匹配:not(a). 因此,您的选择器几乎匹配所有<img>标签。即使您传递一个Jsoup.parse()没有<body>or<html>标记的 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>可以将:not(a) > img其用作选择器:

Elements images = document.select(":not(a) > img");

结果将是这样的:

<img id="a-div-img">
<img id="img">

这样做的问题是它还打印了<img>示例的第一个,它实际上在<a>( #a-div-img) 内。如果这足以满足您的需求,您可以使用此解决方案。

使用纯 CSS 不可能从选择中排除所有<a>标签(至少我还没有找到解决方案)。但是您可以<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");

使用它,原始文档永远不会被修改。


推荐阅读