Crawler IBGE - JSOUP

0 respostas
danilovazb

Olá Senhores, eu fiz(Pelo menos tentei) um crawler que entra no site do IBGE e acessa o link das cidades e faz o download dos CSV contendo as informações que preciso para jogar no B.I. aqui da empresa, mas acho que minha lógica está errada e não está visitando TODOS os links de cidades, ele visita apenas alguns, poderiam me ajudar?

Já tinha perguntado algo parecido em outro lugar, mas não me ajudaram :(

http://www.guj.com.br/6256-crawler-web-dados-ibge-com-jsoup

Segue o código.

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.jsoup.HttpStatusException;
import org.jsoup.Jsoup;
import org.jsoup.UnsupportedMimeTypeException;
import org.jsoup.helper.HttpConnection;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class craw {

	public static void getLinksUF(String URL) throws IOException {

		FileWriter f = new FileWriter("logs.txt", true);
		PrintWriter logs = new PrintWriter(f);

		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm");
		String dataHoraFormatada = sdf.format(d);

		Document doc = Jsoup.connect("http://cidades.ibge.gov.br/xtras/home.php").get();
		Elements questions = doc.select("a[href]");
		for (Element link : questions) {
			if (link.attr("href").contains("uf.php?lang=") && !link.attr("href").contains("lang=_"))
				try {
				System.out.println(link.attr("abs:href"));
				getLinksCidadesPerfil(link.attr("abs:href"));
				
				}catch (SocketTimeoutException e) {
					
				}catch (HttpStatusException e) {
					
				}
		}

		logs.close();

	}
	
	public static void getLinksCidadesPerfil(String URL) throws IOException {

		FileWriter f = new FileWriter("logs.txt", true);
		PrintWriter logs = new PrintWriter(f);

		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm");
		String dataHoraFormatada = sdf.format(d);

		Document doc = Jsoup.connect(URL).get();
		Elements questions = doc.select("a[href]");
		for (Element link : questions) {
			if (link.attr("href").contains("perfil.php?lang=&codmun=") && !link.attr("href").contains("lang=_"))
				System.out.println(link.attr("abs:href"));
				getLinksCidadesSintese(link.attr("abs:href"));
		}

		logs.close();

	}

	public static void getLinksCidadesSintese(String URL) throws IOException {

		FileWriter f = new FileWriter("logs.txt", true);
		PrintWriter logs = new PrintWriter(f);

		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm");
		String dataHoraFormatada = sdf.format(d);

		Document doc = Jsoup.connect(URL).get();
		Elements questions = doc.select("a[href]");
		for (Element link : questions) {
			if (link.attr("href").contains("idtema=16") && !link.attr("href").contains("lang=_") && !link.attr("href").contains("csv.php?lang="))
				System.out.println(link.attr("abs:href"));
				getLinksCidadesClass(link.attr("abs:href"));
		}

		logs.close();

	}
	
	public static void getLinksCidadesClass(String URL) throws IOException {

		InputStream is = null;  
        BufferedInputStream buf = null;  
        FileOutputStream grava = null;  
        
        
		
		FileWriter f = new FileWriter("logs.txt", true);
		PrintWriter logs = new PrintWriter(f);
		
		String outputFolder = "C:\\Users\\rbrasil\\Desktop\\Imagem\\";

		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/YYYY HH:mm");
		String dataHoraFormatada = sdf.format(d);

		Document doc = Jsoup.connect(URL).get();
		Elements titulo = doc.select(".csv");
		Elements valor = doc.select("span[class=municipio titulo]");
		Elements estado = doc.select(".uf");
		for (Element linkTitulo : titulo) {
				try {
					if(linkTitulo.attr("href").contains("idtema=16") && !linkTitulo.attr("href").contains("lang=_EN")){
					System.out.println("Estado: " + estado.text() + " - Cidade: " + valor.text() +" - Link Download: "+ linkTitulo.attr("abs:href"));
					logs.write("Estado: " + estado.text() + " - Cidade: " + valor.text() +" - Link Download: "+ linkTitulo.attr("abs:href"));
					//OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream(new java.io.File(outputFolder + valor.text())));
					//out.write(linkTitulo.attr("abs:href"));
					
					URL url = new URL(linkTitulo.attr("abs:href"));  
			        url.getHost();  
			        url.getFile();  
			        url.getPort();  
			        url.getUserInfo();  
			        URLConnection con = url.openConnection();  
			        buf = new BufferedInputStream(con.getInputStream());  
			        grava = new FileOutputStream("C:\\Users\\rbrasil\\Desktop\\Imagem\\" + estado.text() + " - " + valor.text() + ".csv");  
					
			        int i = 0;  
		            byte[] bytesIn = new byte[1024];  
		            while ((i = buf.read(bytesIn)) >= 0) {  
		                grava.write(bytesIn, 0, i);  
		            }  
					
		            if (buf != null) {  
	                    buf.close();  
	                }  
	                if (grava != null) {  
	                    grava.close();  
	                }  
					}
				}catch (NullPointerException e) {
				
				}	
			
		}

		logs.close();

	}

	public static void main(String[] args) throws IOException {
		getLinksUF("");
	}

}
Criado 26 de setembro de 2013
Respostas 0
Participantes 1