![](/img/trans.png)
[英]Get data of html table from a website in android using Jsoup library,
[英]Jsoup - arrangement of table data from website
我想从https://ms.wikipedia.org/wiki/马来西亚获取表格。 这是我要从网站上获得的表格。
但是结果不是我想要的。
我有2个问题 :
第一个问题是如何将它们像表格一样排列, 行和列的排列方式与图片中的表格相似。 以下是我如何获取数据的源代码。
String URL = "https://ms.wikipedia.org/wiki/Malaysia";
Document doc = Jsoup.connect(URL).get();
Elements trs = doc.select("#mw-content-text > div > table:nth-child(148)");
String currentRow = null;
for (Element tr : trs){
Elements tdDay = tr.select("tr:has(th)");
currentRow = tdDay.text();
System.out.print(currentRow);
}
第二个问题来自我的源代码,这是从所有元素(例如网站https://ms.wikipedia.org/wiki/马来西亚)中的元素中抓取特定数据的最佳方法吗
Elements trs = doc.select("#mw-content-text > div > table:nth-child(148)");
因为从网站上,有3个表类,名称为wikitable。 <table class="wikitable">
。 那么,如何才能只调用特定的表呢?
由于您提供的网站中包含一些wikitable
。 因此,您可以尝试从表中找出数据的选择器,而我发现有<td>
和<th>
。
for (int i = x; i < x; i++) {
Elements trs = doc.select("#mw-content-text > div > table:nth-child(148) > tbody > tr:nth-child(" + i + ") > th");
Elements tds = doc.select("#mw-content-text > div > table:nth-child(148) > tbody > tr:nth-child(" + i + ") > td");
试试这个,而for
循环中的x
是表中的行数,这样它就可以抓取数据
public static void main(String[] args) throws IOException{
String URL = "https://ms.wikipedia.org/wiki/Malaysia";
Document doc = Jsoup.connect(URL).get();
//Select the table which is under the header containing "Trivia"
//having the value "wikitable" for the class attribute
Element table = doc.select("h2:contains(Trivia)+[class=\"wikitable\"]").first();
//then select each row of the table
Elements trs = table.select("tr");
//for each row get first and second child corresponding to column 1 and two of table
for (Element tr : trs){
Element th = tr.child(0);
Element td = tr.child(1);
System.out.printf("%-40s %-40s%n",th.text(), td.text());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.