簡體   English   中英

通過Jsoup的鏈接將表解析為字符串

[英]Parsing a table to a String from a link with Jsoup

就像標題中所說的那樣,我想將表解析為字符串或字符串數​​組,以便從本地公交運營商的網站上獲取純凈的文本。 該網站的表格顯示在頁面中間,其中包含下一站的公交車時間。

我已經有一段時間沒有使用Jsoup了,但是我一輩子都無法弄清楚為什么我的東西不起作用。 我從這里找到的類似問題的答案中嘗試了兩個建議,但都沒有奏效,我擔心表中的Elements實際上是空的,因為它從不返回任何內容...

我從中提取數據的網站如下: http : //www.stcp.pt/pt/viajar/horarios/?paragem=AAL2&t=smsbus (如果未顯示任何表格,那是因為此站僅在夜間使用,因此請嘗試以下操作: http : //www.stcp.pt/pt/viajar/horarios/? paragem=HB1&t=smsbus,該功能應在白天運行)

我的代碼:

import java.io.IOException;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class STCPreaderMain {
    public static void main(String[] args) throws IOException {

        String ParagemID = "AAL2"; // HB1, AAL2 for night

        String getUrl = "http://www.stcp.pt/pt/viajar/horarios/?paragem=REPLACE&t=smsbus";

        getUrl = getUrl.replace("REPLACE", ParagemID);

        String text = "";

        System.out.println(getUrl);

        Document doc = Jsoup.connect(getUrl).get();

        Elements tableElements = doc.select("table#smsBusResults");

        System.out.println(tableElements.text());

        Elements tableHeaderEles = tableElements.select("thead tr th");
        System.out.println("headers");
        for (int i = 0; i < tableHeaderEles.size(); i++) {
            System.out.println(tableHeaderEles.get(i).text());
        }
        System.out.println();

        Elements tableRowElements = tableElements.select(":not(thead) tr");

        for (int i = 0; i < tableRowElements.size(); i++) {
            Element row = tableRowElements.get(i);
            System.out.println("row");
            Elements rowItems = row.select("td");
            for (int j = 0; j < rowItems.size(); j++) {
                System.out.println(rowItems.get(j).text());
            }
            System.out.println();
        }

    }
}

(很抱歉,如果代碼格式錯誤,有時eclipse的自動格式化程序會起作用,而我卻從來都不擅長格式化:()

基本上我的問題是我可以找到聲明名稱為smsBusResults的表的行,但是當我實際去使用table#smsBusResults搜索它時,似乎什么也沒找到...

您找不到表格,因為該表格不在您發布的網址中...
當您轉到該URL時,瀏覽器正在下載其他URL,其中一個是http://www.stcp.pt/pt/itinerarium/soapclient.php?codigo=AAL2&linha=0 ,其中包含您的表。
打開瀏覽器的Developer Tools (按F12鍵)並查看網絡流量-您將看到有多個GET請求,其中一個包含該表。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM