Java Jsoup 不能select table

Java Jsoup can't select table

我最近开始做一个小项目,这样我就可以学习 Jsoup 的基础知识,但是我在特定网站上 select a table 有一些困难。我正在尝试使用 Jsoup 获取 table 但没有成功(见图)http://imgur.com/RC21UBk

我知道我要获取的 table 具有 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);
}

这是一次尝试

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

或者在 select 仅使用特定 class 节点

时使用较短的语法
System.out.println(doc.select("table.meddelande"));

JSoup 支持 selector 语法。因此,您可以将其用于具有特定属性的 select DOM 节点 - 在本例中为 class 属性。

有关 selector 语法中更复杂的选项,请查看此处 http://jsoup.org/cookbook/extracting-data/selector-syntax

在你的代码中

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");

如果这不起作用,那么 HTML 负责 table 的代码可能是由 JavaScript 生成的。在那种情况下,您将无法使用 Jsoup 获取它,但您需要 Selenium web driver, or HtmlUtil

之类的东西

在你的情况下更好select class未读和已读。

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/