【问题标题】:Jsoup take <tr> tag datajsoup 取 <tr> 标签数据
【发布时间】:2020-03-21 06:38:26
【问题描述】:

我正在尝试以下代码,我希望 menuList 有一些节点的结果。 但是 menuList 没有任何节点。这是为什么呢?

    public static void main(String[] args) {
        String connUrl = "http://www.hstree.org/c03/c03_00.php";
        try {
            Document doc = Jsoup.connect(connUrl).get();
            Elements elements = doc.select("table");
            for (Element element : elements) {
                // System.out.println(element.attributes());
                if (element != null && (element.id().equals("1gn") || element.id().equals("2gn"))) {
                    Node childNode = element.childNodes().get(0);
                    List<Node> menuList = childNode.childNodes();
                    System.out.println(element.id()+" menu");
                    for(Node menu : menuList) {
                        System.out.println(menu.childNodes().get(0).toString());
                        System.out.println(" : " + menu.childNodes().get(1).toString());
                    }
                    System.out.println();
                }
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

【问题讨论】:

标签: java web-crawler jsoup


【解决方案1】:

childNodes 返回包括文本在内的所有内容。你需要使用children()Element

String connUrl = "http://www.hstree.org/c03/c03_00.php";
try {
    Document doc = Jsoup.connect(connUrl).get();
    Elements elements = doc.select("table");
    for (Element element : elements) {
        // System.out.println(element.attributes());
        if (element != null && (element.id().equals("1gn") || element.id().equals("2gn"))) {
            Element childNode = element.child(0);
            List<Element> menuList = childNode.children();
            System.out.println(element.id() + " menu");
            for (Element menu : menuList) {
                System.out.println(menu.child(0));
                System.out.println(" : " + menu.child(1));
            }
            System.out.println();
        }
    }
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-31
    • 1970-01-01
    相关资源
    最近更新 更多