Jsoup 使用CSS选择器选择元素

示例

String html = "<!DOCTYPE html>" +
              "<html>" +
                "<head>" +
                  "<title>Hello world!</title>" +
                "</head>" +
                "<body>" +
                  "<h1>Hello there!</h1>" +
                  "<p>First paragraph</p>" +
                  "<p class=\"not-first\">Second paragraph</p>" +
                  "<p class=\"not-first third\">Third <a href=\"page.html\">paragraph</a></p>" +
                "</body>" +
              "</html>";

// 解析文件
Document doc = Jsoup.parse(html);

// 获取文件标题
String title = doc.select("head > title").first().text();
System.out.println(title); // 你好,世界!

Element firstParagraph = doc.select("p").first();

// 获取除第一段外的所有段落
Elements otherParagraphs = doc.select("p.not-first");
// 和...一样
otherParagraphs = doc.select("p");
otherParagraphs.remove(0);

// 获取第三段(其他列表中的第二段)
// 不包括第一段)
Element thirdParagraph = otherParagraphs.get(1);
// 选择:
thirdParagraph = doc.select("p.third");

// 您也可以在元素中进行选择,例如具有href属性的锚点
// 在第三段中。
Element link = thirdParagraph.select("a[href]");
// or the first <h1> element in the document body
Element headline = doc.select("body").first().select("h1").first();

您可以在此处找到支持的选择器的详细概述。