12

我有以下html:

<div>
    <h1>
        <a>1</a>
    </h1>
    <h2>
        <a>2<a>
    </h2>
    <h3>
        <a>3</a>
    </h3>
</div>

有没有比 div > h1 > a, div > h2 > a, div > h3 > a 更好的方法来选择所有锚点。我正在寻找类似 div > (h1,h2,h3) > a

谢谢, 中

4

4 回答 4

17

有可能实现这一点:

div.select("h1,h2,h3").select("a");

或者,如果您只需要 div 内的锚点:

div.select("a");
于 2013-01-05T01:16:20.340 回答
2

您可以使用select("h1,h2,h3")选择 h1,h2,h3 元素

于 2014-02-08T05:36:26.203 回答
0

是的,
你可以使用这样的东西

考虑 div 是你通过这样做得到的 Element 的对象

Element div = document.select("div").first();
Elements anchors = div.select("a");
for(Element e: anchors)
{
  System.out.println("Anchor Text "+e.text()+" HREF VALUE = "+e.attr("href"));
}

这将打印 div 中的所有锚点以及它们包含的文本和 HREF 的值

于 2013-03-05T09:15:25.973 回答
0

希望这可以帮助,

import java.io.File;
import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


public class testXML {

public static void main(String[] args) throws IOException {
    File input = new File("D:\\test.html");
    Document doc = Jsoup.parse(input, "UTF-8");
    Elements divTag = doc.select("div");
    for(Element value: divTag){
        System.out.println(value.text());
    }

    Elements divTagH = doc.select("div").select("h1,h2,h3");
    for(Element value: divTagH){
        System.out.println(value.text());
    }
}

}

输出:

1 2 3 1 2 3

于 2013-11-16T00:09:18.960 回答