0

我想检查是否有spanID 为标签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 或类的元素?

4

1 回答 1

2

您甚至不必使用has

ps 我的选择器工作正常:

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();
  }
}

索引.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>
于 2013-08-14T01:57:27.323 回答