检查是否有输入ID的元素

时间:2013-08-14 00:37:00

标签: java jsoup

我想检查是否有span标记,其ID为trProgramDirector

<span id="MainContent_trProgramDirector">
<span class="contentTitle">Director:</span>&nbsp; 
<span style="font-size: 14px;">Gary David Goldberg</span>
<br />
</span>

我这样做,但它不起作用:

if (document.select("span:has(#MainContent_trProgramDirector)") != null) {
    ...
}

我的问题是,如何检查是否存在具有给定ID或类的元素?

1 个答案:

答案 0 :(得分:2)

您甚至不必使用has

P.S。我的选择器工作正常:

Elements spanWithId = doc.select("span[id$=trProgramDirector]");`

<强> JsoupTest.html

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

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

public class JsoupTest {
  public JsoupTest() {
    try {
      File input = new File("index.html");
      Document doc = Jsoup.parse(input, "UTF-8", "http://localhost");
      System.out.println(doc.toString());

      Elements spanWithId = doc.select("span#MainContent_trProgramDirector");

      if (spanWithId != null) {
        System.out.printf("Found %d Elements\n", spanWithId.size());

        if (!spanWithId.isEmpty()) {
          Iterator<Element> it = spanWithId.iterator();
          Element element = null;
          while (it.hasNext()) {
            element = it.next();
            System.out.println(element.toString());
          }
        }
      }
    } catch (IOException e) { }
  }

  public static void main(String[] args) {
    new JsoupTest();
  }
}

<强>的index.html

<!html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <span id="MainContent_trProgramDirector">
    <span class="contentTitle">Director:</span>&nbsp; 
    <span style="font-size: 14px;">Gary David Goldberg</span>
    <br />
    </span>
  </body>
</html>

<强>输出

... Omitted for readability.
Found 1 Elements
<span id="MainContent_trProgramDirector"> <span class="contentTitle">Director:</span>&nbsp; <span style="font-size: 14px;">Gary David Goldberg</span> <br /> </span>
相关问题