0

I copied a simple web crawler from the internet and then started to run the application in a test class. Every time i try to run the application I get "Exception in thread "main" java.lang.NoClassDefFoundError: org/jsoup/Jsoup" error. I first imported the jsoup jar as a externaljar in a Libary, because I needed it for the http stuff.

Error messages:

Exception in thread "main" java.lang.NoClassDefFoundError: org/jsoup/Jsoup
    at com.copiedcrawler.SpiderLeg.crawl(SpiderLeg.java:35)
    at com.copiedcrawler.Spider.search(Spider.java:40)
    at com.copiedcrawler.SpiderTest.main(SpiderTest.java:9)
Caused by: java.lang.ClassNotFoundException: org.jsoup.Jsoup
    at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:602)
    at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178)
    at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
    ... 3 more

Spider Class

package com.copiedcrawler;


import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class Spider
{
  private static final int MAX_PAGES_TO_SEARCH = 10;
  private Set<String> pagesVisited = new HashSet<String>();
  private List<String> pagesToVisit = new LinkedList<String>();

  public void search(String url, String searchWord)
  {
      while(this.pagesVisited.size() < MAX_PAGES_TO_SEARCH)
      {
          String currentUrl;
          SpiderLeg leg = new SpiderLeg();
          if(this.pagesToVisit.isEmpty())
          {
              currentUrl = url;
              this.pagesVisited.add(url);
          }
          else
          {
              currentUrl = this.nextUrl();
          }
          leg.crawl(currentUrl); // Lots of stuff happening here. Look at the crawl method in
                                 // SpiderLeg
          boolean success = leg.searchForWord(searchWord);
          if(success)
          {
              System.out.println(String.format("**Success** Word %s found at %s", searchWord, currentUrl));
              break;
          }
          this.pagesToVisit.addAll(leg.getLinks());
      }
      System.out.println("\n**Done** Visited " + this.pagesVisited.size() + " web page(s)");
  }


  /**
   * Returns the next URL to visit (in the order that they were found). We also do a check to make
   * sure this method doesn't return a URL that has already been visited.
   * 
   * @return
   */
  private String nextUrl()
  {
      String nextUrl;
      do
      {
          nextUrl = this.pagesToVisit.remove(0);
      } while(this.pagesVisited.contains(nextUrl));
      this.pagesVisited.add(nextUrl);
      return nextUrl;
  }
}

SpiderLeg class

package com.copiedcrawler;


import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SpiderLeg
{
    // We'll use a fake USER_AGENT so the web server thinks the robot is a normal web browser.
    private static final String USER_AGENT =
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.1 (KHTML, like Gecko) Chrome/13.0.782.112 Safari/535.1";
    private List<String> links = new LinkedList<String>();
    private Document htmlDocument;


    /**
     * This performs all the work. It makes an HTTP request, checks the response, and then gathers
     * up all the links on the page. Perform a searchForWord after the successful crawl
     * 
     * @param url
     *            - The URL to visit
     * @return whether or not the crawl was successful
     */
    public boolean crawl(String url)
    {
        try
        {
            Connection connection = Jsoup.connect(url).userAgent(USER_AGENT);
            Document htmlDocument = connection.get();
            this.htmlDocument = htmlDocument;
            if(connection.response().statusCode() == 200) // 200 is the HTTP OK status code
                                                          // indicating that everything is great.
            {
                System.out.println("\n**Visiting** Received web page at " + url);
            }
            if(!connection.response().contentType().contains("text/html"))
            {
                System.out.println("**Failure** Retrieved something other than HTML");
                return false;
            }
            Elements linksOnPage = htmlDocument.select("a[href]");
            System.out.println("Found (" + linksOnPage.size() + ") links");
            for(Element link : linksOnPage)
            {
                this.links.add(link.absUrl("href"));
            }
            return true;
        }
        catch(IOException ioe)
        {
            // We were not successful in our HTTP request
            return false;
        }
    }


    /**
     * Performs a search on the body of on the HTML document that is retrieved. This method should
     * only be called after a successful crawl.
     * 
     * @param searchWord
     *            - The word or string to look for
     * @return whether or not the word was found
     */
    public boolean searchForWord(String searchWord)
    {
        // Defensive coding. This method should only be used after a successful crawl.
        if(this.htmlDocument == null)
        {
            System.out.println("ERROR! Call crawl() before performing analysis on the document");
            return false;
        }
        System.out.println("Searching for the word " + searchWord + "...");
        String bodyText = this.htmlDocument.body().text();
        return bodyText.toLowerCase().contains(searchWord.toLowerCase());
    }


    public List<String> getLinks()
    {
        return this.links;
    }

}

SpiderTest class

package com.copiedcrawler;

public class SpiderTest {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Spider s1 = new Spider();
        s1.search("https://www.w3schools.com/html/", "html");
    }

}
vazun
  • 194
  • 2
  • 15
  • Works fine for me. What Eclipse version are you using and what java version are you using? – Abra Sep 28 '20 at 17:47
  • Here is a massively long [Stack Overflow answer](https://stackoverflow.com/questions/18093928/what-does-could-not-find-or-load-main-class-mean/18093929#18093929) about the exception you have mentioned.... And here is brief but direct answer about [importing JAR's](https://stackoverflow.com/questions/26104786/classpath-jar-files-in-eclipse) using Eclipse. – Y2020-09 Sep 28 '20 at 18:04
  • If you have a `module-info.java` file, delete it. Otherwise, show how you have added the jsoup JAR to the Java Build Path. – howlger Sep 28 '20 at 18:27
  • I am using the Eclipse June 2020 version and the JDK 14.0.2 – vazun Oct 01 '20 at 05:52
  • At first I added the Jsoup by clicking on the Projekt on properties on build path and then add external jar. Later I tried it with a libs folder but this didn’t work either – vazun Oct 01 '20 at 05:53
  • I had no modulinfo – vazun Oct 01 '20 at 05:54

2 Answers2

1

You might have added the Jsoup Jar File into the Modulepath.

You need to add the JAR file to classpath.

Follow the below steps:

  1. Remove the Jsoup JAR from the libraries.
  2. Project->Build Path->Configure Build Path->Libraries->ClassPath->Add External JARs.
  3. Apply and Close.
  4. Re-run the project.

Now, It should work.

JavaJunkie
  • 11
  • 2
0

Based on stacktrace you are running java program from command line and you forgot to add jsoup into class path. Try running

java -cp classes:libs/jsoup.jar com.copiedcrawler.SpiderTest

Where classes is your program compiled and libs is a folder with libraries.

Boris
  • 1,054
  • 1
  • 13
  • 23
  • I added the jar by properties of the projekt --> java build bath --> add external jar --> jar file from the download folder. Now I tried it with a lib folder, but it didnt work as well. Maybe its because I use the false java version. Currently I am using the newest eclipse version and the 14 JDK. I dont really know if I need a specific java version for jars or this jar. – vazun Sep 29 '20 at 19:22
  • In this case I would highly recommend to use Maven for dependency management. Then you don't need to manually setup all libraries and depend on exact IDE. – Boris Sep 29 '20 at 20:46
  • Since you "copied this from the internet", you should also pass that recommendation on to the author of the software that you copied. – Stephen C Dec 09 '20 at 00:39