简体   繁体   English

在jsoup中获取特定标签类型的下一个元素

[英]Get next element of specific tag type in jsoup

I'm iterating through a list of elements using jsoup, but periodically need to find one element that doesn't occur directly after the current element. 我正在使用jsoup遍历元素列表,但需要定期查找一个不会在当前元素之后直接出现的元素。

For example, if I'm iterating through and come to an img tag, I want to find the very next a tag occurring after that img tag. 例如,如果我要遍历并转到img标签,我想找到紧接在该img标签之后的下a标签。 But, there could be a few tags in between the two. 但是,两者之间可能有一些标签。

Here's some example code: 这是一些示例代码:

for (Element e : elements) {
    if (e.tagName().equalsIgnoreCase("img")) {
        // Do some stuff with "img" tag
        // Now, find the next tag in the list with tag <a>
    }

    // Do some other things before the next loop iteration
}

I thought something like e.select("img ~ a") should work, but it returns no results. 我认为类似e.select("img ~ a")应该可以工作,但是它不会返回任何结果。

What's a good way of doing this in jsoup? 在jsoup中执行此操作的好方法是什么?

This appears to be a way of accomplishing the stated goal. 这似乎是实现既定目标的一种方式。 Not sure it's the most efficient, but it is the most straightforward. 不确定它是否最有效,但是最直接。

Element node = e.nextElementSibling();
while (node != null && !node.tagName().equalsIgnoreCase("a")) {
    node = node.nextElementSibling();
}

I was hoping for a way to run the equivalent of e.nextElementSibling("a") . 我希望有一种方法可以运行等效于e.nextElementSibling("a") Perhaps something for me to contribute back to jsoup ;-) 也许我可以为jsoup做出贡献;-)

Use the nextElementSibling() method. 使用nextElementSibling()方法。

Inside your if statement add the following code: 在if语句中,添加以下代码:

Element imgNext = e.nextElementSibling();
do {
    Element a = imgNext.select("a[href]").first();         
} while (imgNext!=null && a==null);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM