Categorías
Java Projects

¿Cómo escribir un rastreador usando Java?

En realidad, escribir un programa rastreador de Java no es muy difícil utilizando las API existentes, pero escribir su propio rastreador probablemente le permitirá realizar todas las funciones que desee. Debería ser muy interesante obtener información específica de Internet. Proporcionar el código no es fácil, pero busqué y encontré el algoritmo básico para un rastreador.

Estarás reinventando la rueda, sin duda. Pero aquí está lo básico:

1. Una lista de URL no visitadas: inserte esto con una o más páginas de inicio.
2. Una lista de URL visitadas, para que no dé vueltas en círculos.
3. Un conjunto de reglas para las URL que no le interesan, por lo que no indexa toda Internet.
4. Es necesario poner estos almacenados en una base de datos, ya que el rastreador puede detenerse y necesitar reiniciar con el mismo lugar sin perder el estado.

El algoritmo es el siguiente.

while(list of unvisited URLs is not empty) {
      take URL from list
      fetch content
      record whatever it is you want to about the content
      if content is HTML {
          parse out URLs from links
          foreach URL {
                 if it matches your rules
                 and it's not already in either the visited or unvisited list
                 add it to the unvisited list
          }
     }
}

Discutamos si decides hacer uno. Ahora el problema aquí es la lista de URL.

¿Dónde encontrar la lista de sitios web? Supongo que solo necesita encontrarlo en algunos directorios existentes o en algún lugar, o incluso manualmente.

Jsoup es un analizador de HTML que podría hacer que la parte de análisis sea muy fácil e interesante de hacer.

Actualización: he hecho un sencillo tutorial sobre rastreadores.

El siguiente código todavía tiene problemas.

  ¿Cómo hacer un rastreador web usando Java?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
 
 
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
 
public class FileCrawler {
 
	public static void main(String[] args) throws IOException {
 
		File dir = new File(".");
		String loc = dir.getCanonicalPath() + File.separator + "record.txt";
		FileWriter fstream = new FileWriter(loc, true);
		BufferedWriter out = new BufferedWriter(fstream);
		out.newLine();
		out.close();
 
		processPage("http://cis.udel.edu");
 
		File file = new File(loc);
 
		if (file.delete()) {
 
		}
	}
 
	// givn a String, and a File
	// return if the String is contained in the File
	public static boolean checkExist(String s, File fin) throws IOException {
 
		FileInputStream fis = new FileInputStream(fin);
		// //Construct the BufferedReader object
		BufferedReader in = new BufferedReader(new InputStreamReader(fis));
 
		String aLine = null;
		while ((aLine = in.readLine()) != null) {
			// //Process each line
			if (aLine.trim().contains(s)) {
				//System.out.println("contains " + s);
				in.close();
				fis.close();
				return true;
			}
		}
 
		// do not forget to close the buffer reader
		in.close();
		fis.close();
 
		return false;
	}
 
	public static void processPage(String URL) throws IOException {
 
		File dir = new File(".");
		String loc = dir.getCanonicalPath() + File.separator + "record.txt";
 
		// invalid link
		if (URL.contains(".pdf") || URL.contains("@") 
				|| URL.contains("adfad") || URL.contains(":80")
				|| URL.contains("fdafd") || URL.contains(".jpg")
				|| URL.contains(".pdf") || URL.contains(".jpg"))
			return;
 
		// process the url first
		if (URL.contains("cis.udel.edu") && !URL.endsWith("/")) {
 
		} else if(URL.contains("cis.udel.edu") && URL.endsWith("/")){
			URL = URL.substring(0, URL.length()-1);
		}else{
			// url of other site -> do nothing
			return;
		}
 
		File file = new File(loc);
 
		// check existance
		boolean e = checkExist(URL, file);
		if (!e) {
			System.out.println("------ :  " + URL);
			// insert to file
			FileWriter fstream = new FileWriter(loc, true);
			BufferedWriter out = new BufferedWriter(fstream);
			out.write(URL);
			out.newLine();
			out.close();
 
			Document doc = null;
			try {
				doc = Jsoup.connect(URL).get();
			} catch (IOException e1) {
				e1.printStackTrace();
				return;
			}
 
			if (doc.text().contains("PhD")) {
				//System.out.println(URL);
			}
 
			Elements questions = doc.select("a[href]");
			for (Element link : questions) {
				processPage(link.attr("abs:href"));
			}
		} else {
			// do nothing
			return;
		}
 
	}
}
  ¿Cómo hacer un rastreador web usando Java?

Por Programación.Click

Más de 20 años programando en diferentes lenguajes de programación. Apasionado del code clean y el terminar lo que se empieza. ¿Programamos de verdad?

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *