java - JSoup - 选择不在链接内的图像
问题描述
如何选择不在链接元素内的所有图像?
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>
标签。即使您传递一个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");
使用它,原始文档永远不会被修改。
推荐阅读
- sql - 需要帮助旋转数据
- javascript - 如何从云函数返回 Firebase 时间戳
- google-cloud-platform - Cloud Composer 工作器无法连接到外部数据库
- python - 预处理时测试/删除不可解码的字节
- amazon-web-services - Elastic Beanstalk:`eb local run` 启动容器乱序,导致启动失败
- macos - 在 MacOS Catalina 上找不到 nix-env 或 nix-build
- multithreading - 使克隆的线程 pthread 兼容
- docker - fedora32 上 pod 的 minikube docker 映像上的 i/o 超时 ImagePullBackOff 问题
- css - 如何在 Vue.js 中向 Konva 层添加自定义 CSS 样式?
- python - 冒号运算符在python中导致未定义的行为