如何解析表格第3列的单元格?

我试图使用Jsoup解析

的第3列的单元格。

这是HTML:

 
Linje Destination Nästa tur (min)   Därefter  
1 Hovshaga Kurortsv.55 --
1 Hovshaga via Resecentrum21 --
1 Teleborg5 45

这是我的代码尝试抛出NullPointerException

  URL url = null; try { url = new URL("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("1"); Document doc = null; try { System.out.println("2"); doc = Jsoup.parse(url, 3000); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("3"); Element table = doc.select("table[title=Avgångar:]").first(); System.out.println("3"); Iterator it = table.select("td").iterator(); //we know the third td element is where we wanna start so we call .next twice it.next(); it.next(); while(it.hasNext()){ // do what ever you want with the td element here System.out.println("::::::::::"+it.next()); //iterate three times to get to the next td you want. checking after the first // one to make sure // we're not at the end of the table. it.next(); if(!it.hasNext()){ break; } it.next(); it.next(); } 

直到第二个System.Out.Println("3"); 然后它卡住了。

这种方法非常混乱,你没有告诉NPE发生在哪一行,所以很难直截了当地回答你的问题。

除此之外,我建议不要采取艰难而容易出错的方式。 因为

已经有一个id属性,它应该在整个文档中是唯一的,所以只需使用ID选择器#someid 。 此外,您可以使用索引选择器获取第3列的单元格:eq(index) (注意:它基于零!)。

所以,那些简单的行应该这样做:

 Document document = Jsoup.connect("http://wap.nastabuss.se/its4wap/QueryForm.aspx?hpl=Teleborg+C+(V%C3%A4xj%C3%B6)").get(); Elements nextTurns = document.select("#GridViewForecasts td:eq(2)"); for (Element nextTurn : nextTurns) { System.out.println(nextTurn.text()); } 

这导致:

 50 30 10 18 3 24 

而已。

我强烈建议花一些时间来正确学习CSS选择器语法,因为Jsoup是围绕它构建的。

也可以看看:

  • Jsoup CSS选择器语法
  • Jsoup Selector API
  • W3 CSS3选择器规范

我认为最好的解决方案是使用get(); 从多个elements获取单个element方法。

 Document doc = Jsoup.connect("your_url").get(); Elements table = doc .getElementById("id_of_your_table"); Element tr = table.select("tr").get(2); // this will get 3rd tr //if you need 3rd column of 3rd row then Element 3rdtd = tr.select("td").get(2); Log.i("3rd Column of 3rd Row", 3rdtd.text().toString()); 

希望它会有所帮助。