gpt4 book ai didi

java - JSoup - 选择不在链接内的图像

转载 作者:行者123 更新时间:2023-11-30 05:38:41 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com