所以我一直在尝试从这个网站解析城市:https://en.wikipedia.org/wiki/List_of_cities_in_Switzerland
我是jsoup的新手,所以我试图获取城市的名字,但我得到了城市的每个元素。
Document doc = Jsoup.connect("https://en.wikipedia.org/wiki/List_of_cities_in_Switzerland").userAgent("Mozilla").get();
String title = doc.title();
Elements test = doc.select("table.wikitable").select("tbody").select("tr");
for (Element link : test) {
Elements temp = link.select("td").select("a");
System.out.println(temp.text());
}
例如,我得到了这个Aarberg Aarberg Bern,而我只想要Aarberg
答案 0 :(得分:3)
通过添加如此多的select
次调用,您会使事情过于复杂。您可以使用一个select
来简化代码,在其中指向要查找的每个元素。用空间来描述祖先 - 后代关系。
无论如何select("td")
选择td
中的每个tr
。然后,您将收集这些所选a
中的每个td
链接。
要仅选择每个td
中的第一个tr
,您可以使用选择器td:eq(0)
。然后,您可以从每个a
中选择每个td
。
无论如何,你的代码被简化为更像:
Elements links = doc.select("table.wikitable tr td:eq(0) a");
for (Element link : links) {
System.out.println(link.text());
}
要详细了解选择器,请访问http://jsoup.org/cookbook/extracting-data/selector-syntax,其中可以找到:eq(n)
:eq(n)
:找到其兄弟索引等于n
的元素;例如form input:eq(1)