Domanda

I am new to Jsoup I am suppose to do a screen scraping to obtain a hierarchy of links. I am able to get the links from the first page but I need to know how I can go deeper and get the link of each link. This is what i have so far. It prints out all the URLs but i want to go deeper and print the URL of each one too or if its too much at least i want to pick one URL example "* a: http://www.w3schools.com/html/default.asp (Learn HTML)" it is from the output and print all its child URL.

import org.jsoup.Jsoup;
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;

/**
 * Example program to list links from a URL.
 */
public class ListLinks {
    public static void main(String[] args) throws IOException {

    String url = "http://www.w3schools.com/";
    print("Fetching %s...", url);

    Document doc = Jsoup.connect(url).get();
    Elements links = doc.getElementsByTag("a");


    print("\nLinks: (%d)", links.size());
    for (Element link : links) {
       print(" * a: <%s>  (%s)", link.absUrl("href") /*link.attr("href")*/, trim(link.text(), 35));     
    }
    }

    private static void print(String msg, Object... args) {
    System.out.println(String.format(msg, args));
    }

    private static String trim(String s, int width) {
    if (s.length() > width)
        return s.substring(0, width-1) + ".";
    else
        return s;
    }
}

Output:

Fetching http://www.w3schools.com/...

Links: (127)
 * a: <>  ()
 * a: <http://www.w3schools.com/html/default.asp>  (Learn HTML)
 * a: <http://www.w3schools.com/html/html5_intro.asp>  (Learn HTML5)
 * a: <http://www.w3schools.com/css/default.asp>  (Learn CSS)
 * a: <http://www.w3schools.com/css3/default.asp>  (Learn CSS3)
     ...
     ...

There's more URLs but i didn't want to display them all

È stato utile?

Soluzione

You can iterate on each child URI and create a new JSOUP Document and then collect all the child links

example pseudocode:

download(String toplevelURI, int level) {
  if (level > MAX_LEVEL) {
    return; //termination condition
  }
  Document doc = Jsoup.connect(url).get();
  Elements links = doc.getElementsByTag("a");
  for (Element link : links) {
     String url = link.absUrl("href");
     link.add(url); //store the current level of link
     download(url, level++); //get all children of current link
  }
}

There are few things to take care of

  • Till what depth you want to download (MAX_DEPTH)
  • The links needs to be stored in a tree structure to keep parent link / child link relationship
  • The code is doing depth first i.e. it will follow a link until it reaches a page where there are no link or reaches MAX_DEPTH. try changing it so its depth first
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top