【问题标题】:How to get contents of a specific html element in Jsoup?如何在 Jsoup 中获取特定 html 元素的内容?
【发布时间】:2016-12-13 06:32:10
【问题描述】:

我目前正在尝试使用 jsoup 从维基百科获取表格及其内容/格式。但是,当我运行此代码时,我在第 29 行收到错误:

project.wikiclass.main(wikiclass.java:29) 的线程“main”java.lang.NullPointerException 中的异常

我不知道有什么方法可以获取数据。我目前使用的名称似乎不正确。该表位于:

https://en.wikipedia.org/wiki/Liverpool_F.C.#First-team_squad

在检查元素中,需要的最外层元素称为<table border="0">

但是,我无法使用名称边框通过 id 获取元素。如果有人能告诉我如何获得这个元素或它的真名是什么,那将会很有帮助。通过转到链接页面并突出显示名称列表并使用检查元素可以找到该元素。

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 wikiclass {

  public static void main(String[] args) {

    Document doc;
    try {

        // need http protocol
        doc = Jsoup.connect("https://en.wikipedia.org/wiki/Liverpool_F.C.").get();

        // get page title
        String title = doc.title();
        System.out.println("title : " + title);

        //make html file
        StringBuffer html = new StringBuffer();

        // get all links
        String table = doc.getElementById("border").outerHtml();
        System.out.println(table);
        /*for (Element link : links) {

            // get the value from href attribute
            System.out.println("\nlink : " + link.attr("href"));
            System.out.println("text : " + link.text());

        }*/

    } catch (IOException e) {
        e.printStackTrace();
    }

  }

}

【问题讨论】:

    标签: java html parsing web-scraping jsoup


    【解决方案1】:

    我认为你有 NPE,因为 Jsoup 找不到这个元素。

    你可以试试这个

     Elements table = doc.select("div#bodyContent table.infobox");
    

    然后迭代ech元素并获取信息

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-04
      • 2013-02-09
      相关资源
      最近更新 更多