“线程“main”java.Lang.NullPointerException 中的异常”错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21868795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 11:10:01  来源:igfitidea点击:

"Exception in thread "main" java.Lang.NullPointerException" Error

javaeclipseweb-scrapingjsoup

提问by Hen Sapir

I am trying to run a web scraper in Eclipse that, using Jsoup, that can take the names of the professors on this page: yu.edu/faculty and print them out. This is my code:

我正在尝试在 Eclipse 中运行一个网络抓取工具,使用 Jsoup,它可以获取此页面上教授的姓名:yu.edu/faculty 并将它们打印出来。这是我的代码:

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

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

        // fetches & parses HTML        
        String url = "http://yu.edu/faculty/";
        Document document = Jsoup.connect(url).get(); 

        // Extract data
        Element content = document.getElementById("mainlist");
        Elements names = content.getElementsByTag("a");


        // Output data
        for (Element name : names) {
            System.out.println("Name: " + name.text());
        }
    }

}

I am getting this error:

我收到此错误:

Exception in thread "main" java.lang.NullPointerException
at YUscraper.main(YUscraper.java:18)

I am relatively new to this so pardon me if I am missing something really evident. I used many examples I have seen to get to this point, but I still don't understand what throws IOException is for and what it means that an exception was found. Please help, thanks!

我对此比较陌生,所以如果我遗漏了一些非常明显的东西,请原谅我。我使用了很多我见过的例子来达到这一点,但我仍然不明白 throws IOException 是什么以及发现异常意味着什么。请帮忙,谢谢!

采纳答案by Vivek Vermani

Line 18 is

第 18 行是

Elements names = content.getElementsByTag("a");

元素名称 = content.getElementsByTag("a");

Seems like there is no tag with id "mainlist" in the html retrieved from http://yu.edu/faculty/.

http://yu.edu/faculty/检索到的 html 中似乎没有 id 为“mainlist”的标签。

Seems like you were trying to access tag main-nav instead of mainlist.

似乎您试图访问标签 main-nav 而不是 mainlist。

回答by harshit

Line Element content = document.getElementById("mainlist");

线 Element content = document.getElementById("mainlist");

content is returned as null, so null.getElementsByTagis giving the error .. Looks like html doesn't have element by 'mainlist'

内容返回为空,所以null.getElementsByTag给出错误.. 看起来 html 没有“mainlist”的元素