0

有没有办法使用 jsoup 检查表是否有特定行?

我遇到了一个java.lang.IndexOutOfBoundsException: Invalid location 1, size is 1例外,我从表格中获取信息的代码是:

  docTide = Jsoup.connect("http://www.mhpa.co.uk/search-tide-times/").timeout(600000).get();
  Elements tideTimeOdd = docTide.select("div.tide_row.odd div:eq(0)");
  Elements tideTimeEven = docTide.select("div.tide_row.even div:eq(0)");
  Elements tideHightOdd = docTide.select("div.tide_row.odd div:eq(2)");
  Elements tideHightEven = docTide.select("div.tide_row.even div:eq(2)");
  Element firstTideTime = tideTimeOdd.first();
  Element secondTideTime = tideTimeEven.first();
  Element thirdTideTime = tideTimeOdd.get(1);
  Element fourthTideTime = tideTimeEven.get(1);

发生异常是因为有时该表按此顺序只有 3 行而不是 4 行;奇偶 奇偶

这是导致问题的最后一个“偶数”行。

  <div class="tide_row odd"> 
  <div class="time">00:57</div>
  <div class="height_m">4.9</div>
  <div class="height_f">16,1</div>
  <div class="range_m">1.9</div>
  <div class="range_f">6,3</div>
  </div>
  <div class="tide_row even">
  <div class="time">07:23</div>
  <div class="height_m">2.9</div>
  <div class="height_f">9,6</div>
  <div class="range_m">2</div>
  <div class="range_f">6,7</div>
  </div>
  <div class="tide_row odd">
  <div class="time">13:46</div>
  <div class="height_m">5.1</div>
  <div class="height_f">16,9</div>
  <div class="range_m">2.2</div>
  <div class="range_f">7,3</div>
  </div>
  <div class="tide_row even">
  <div class="time">20:23</div>
  <div class="height_m">2.8</div>
  <div class="height_f">9,2</div>
  <div class="range_m">2.3</div>
  <div class="range_f">7,7</div>
  </div>
4

2 回答 2

2

要简单地检查Elements对象的大小,请使用该size()方法来确定它是否存在。

要检查某个Element使用该contains()方法。

您还可以考虑使用循环来遍历集合Element中的所有对象Elements


if(tideTimeEven.size() > 1)
    //Do something
于 2013-10-04T21:09:03.110 回答
1

你可以做

if (tideTimeEven.size() > 1) {
    Element fourthTideTime = tideTimeEven.get(1);
}
于 2013-10-04T21:08:23.733 回答