[英]Java get Array from parsed html table
我想從 Java 數組中的表中獲取數據
我已經解析了表中的數據並將其存儲在一個字符串中。 但是每一行都是我的字符串中的一個新行。 我想在一個數組中獲取所有行。
我的字符串 x 在一個新行中打印出每個價格:
$25,913,000
$40,388,000
$48,995,000
$3,956,000
$12,087,000
$131,339,000
$170,799,000
$41,304,000
$0
$0
$22,283,000
$0
$365,725,000
$55,888,000
$20,748,000
$40,230,000
$116,866,000
$93,735,000
$45,180,000
$2,797,000
$0
$0
$258,578,000
$40,201,000
$0
$70,400,000
$0
($3,454,000)
$107,147,000
$365,725,000
那是我的代碼
try {
org.jsoup.nodes.Document doc = (org.jsoup.nodes.Document) Jsoup.connect(url_balance_year).userAgent("Mozilla/5.0").get();
Elements trs = doc.select("tr");
for (org.jsoup.nodes.Element tr : trs) {
Elements tds = tr.select(".td_genTable");
if (tds.size() == 0) continue;
org.jsoup.nodes.Element td = tds.first().siblingElements().first();
org.jsoup.nodes.Element td1 = tds.first().nextElementSibling();
org.jsoup.nodes.Element td2 = tds.first().nextElementSibling().nextElementSibling();
org.jsoup.nodes.Element td3 = tds.first().nextElementSibling().nextElementSibling().nextElementSibling();
org.jsoup.nodes.Element td4 = tds.first().nextElementSibling().nextElementSibling().nextElementSibling().nextElementSibling();
String x = td1.ownText();
System.out.println(x);
//Here I want to all the prices from String x in one Array
}
} catch (Exception e) {
}
如何在一個數組中獲取 String x 的所有價格?
而不是只用System.out.println(x);
打印字符串System.out.println(x);
您可以將它們添加到列表中
// declare a list first
List<String> list = new ArrayList<>();
...
list.add(x);
代替
org.jsoup.nodes.Element td = tds.first().siblingElements().first();
org.jsoup.nodes.Element td1 = tds.first().nextElementSibling();
org.jsoup.nodes.Element td2 = tds.first().nextElementSibling().nextElementSibling();
org.jsoup.nodes.Element td3 = tds.first().nextElementSibling().nextElementSibling().nextElementSibling();
org.jsoup.nodes.Element td4 = tds.first().nextElementSibling().nextElementSibling().nextElementSibling().nextElementSibling();
String x = td1.ownText();
System.out.println(x);
和
// create a list of Strings to store texts
List<String> list = new ArrayList<String>();
// to avoid calling first() many times assign the result to a variable
Element td = tds.first();
// instead of chaining next...next...next... you can iterate over all the siblings using iterator() and while loop
Iterator<Element> iter = td.siblingElements().iterator();
while (iter.hasNext()) {
// every sibling is assigned to a new variable
Element sibling = iter.next();
// sibling text is added to list
list.add(sibling.ownText());
}
// display whole list
System.out.println(list);
// and if you really need an array you can transform it
String[] arrayWithTexts = list.toArray(new String[list.size()]);
您將丟失一些導入,但您的 IDE 將幫助您解決並推薦修復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.