簡體   English   中英

Java Jsoup無法選擇表

[英]Java Jsoup can't select table

我最近開始從事一個小型項目,因此我可以學習Jsoup的基礎,但是在特定網站上選擇表格有些困難。 我正在嘗試使用Jsoup來獲取表,但沒有成功(參見圖片) http://imgur.com/RC21UBk

我知道我要獲取的表具有class =“ meddelande”,並且也位於具有相同class =“ meddelande”的表單元素內。 網站的HTML代碼: http//pastebin.com/ufRDhLSy

我正在嘗試獲取紅色標記的區域,對此有任何想法嗎? 提前致謝! :)

我的代碼:

public void startMessage(String cookie1) {
    try {
        doc1 = Jsoup.connect("https://nya.boplats.se/minsida/meddelande")
                .timeout(0).cookie("Boplats-Session", cookie1)
                .get();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Elements tables = doc1.select("form.meddelande");
    Elements table = tables.select("table.meddelande");
    System.out.println(table);
}

在你的代碼中

Elements tables = doc1.select("form.meddelande");    
Elements table = tables.select("table.meddelande");

您正在嘗試使用class屬性meddelande訪問form ,但是從鏈接的HTML源代碼中, meddelandeid ,而不是class ,所以不是

form.meddelande

你應該使用

form#meddelande
    ^--# means id, dot represents class

所以嘗試

Elements tables = doc.select("form#meddelande");    
Elements table = doc.select("table.meddelande");

或更簡單

Elements table = doc.select("form#meddelande table.meddelande");

如果這不起作用,則可能由JavaScript生成負責表的HTML代碼。 在這種情況下,您將無法通過Jsoup獲得它,但是您將需要Selenium Web driverHtmlUtil之類的東西

這是一個嘗試

Document doc = Jsoup.connect("http://pastebin.com/raw.php?i=ufRDhLSy").get();
System.out.println(doc.select("table[class=meddelande]"));

或僅選擇具有特定類的節點時使用較短的語法

System.out.println(doc.select("table.meddelande"));

JSoup支持選擇器語法。 因此,您可以使用它來選擇具有特定屬性的DOM節點-在本例中為class屬性。

有關選擇器語法中更復雜的選項,請參見此處http://jsoup.org/cookbook/extracting-data/selector-syntax

根據您的情況,最好選擇未讀和已讀的課程。

import java.io.File;
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 JsoupSO {

    public static void main(String args0[]) throws IOException {
        Document doc;
        Elements elements;

        doc = Jsoup.parse(new File("path_to_file or use connect for URL"), "UTF-8");

        elements = doc.getElementsByClass("unread");
        for (Element element : elements) {
            System.out.println(element);
        }

        elements = doc.getElementsByClass("read");
        for (Element element : elements) {
            System.out.println(element);
        }
    }

}

輸出: http : //pastebin.com/CwG1cL5T

是的,請閱讀他們的食譜http://jsoup.org/

暫無
暫無

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

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