Olá a todos
Tenho um programa que pesquisa uma frase no google e guarda o titulo e o url de cada um desses resultados numa classe chamada Resultados. No entanto, quando o dou uma frase para pesquisar o programa apenas me retorna o primeiro resultado obtido em vez da lista de resultados. Obrigado pela ajuda!
Classe Main:
package com.newschecker.demochecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.newschecker.demochecker.domain.Resultados;
import com.newschecker.demochecker.service.NewsCheckerService;
@SpringBootApplication
public class DemoCheckerApplication implements CommandLineRunner{
public static void main(String[] args) {
SpringApplication.run(DemoCheckerApplication.class, args);
}
@Autowired
NewsCheckerService service;
@Override
public void run(String... args) throws Exception {
Resultados re = service.getResultadosGoogleProntos("Trump perdeu a peruca numa turbina de avião");
System.out.print(re);
}
}
Classe Service
package com.newschecker.demochecker.service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.newschecker.demochecker.domain.Resultados;
@Service
public class NewsCheckerService {
private static Logger log = LoggerFactory.getLogger(NewsCheckerService.class);
public Resultados getResultadosGoogleProntos(String noticia) {
Resultados resultados = new Resultados();
noticia = isolaPalavrasChave(noticia);
try {
resultados = searchGoogle(noticia);
} catch (IOException e) {
log.error(e.getMessage(), e.getCause());
}
if (!isEmpty(resultados)) {
return resultados;
}
else {
return null;
}
}
// pattern for extracting the titulosResultados such as www.codeforeach.com/java/ ( domain
// name + path )
private static final Pattern p = Pattern
.compile("([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}(/[^&]*)*");
public String isolaPalavrasChave(String frase) {
String palavrasRetirar = " o - a - de - dos - das - na - nas - nos - no -.- quase -(-)-[-]- " +
" que - se - com - que - é - um - as - os - para - do - da - no - nas - " +
" nos - na - para -...-,- uma - umas - numa - num - ao - aos - e -€-r$-?- já - ter "
+ " that - is - are - her - his - i - am - you - yours - him - to - of ";
String[] palavrasChaveSeparadas = palavrasRetirar.split("-");
for (int x = 0; x < palavrasChaveSeparadas.length; x++){
frase = frase.replace(palavrasChaveSeparadas[x], " ");
}
frase = frase.replace(" ", " ");
return frase;
}
String retiraAcentos(String input){
return input.replaceAll("á|à|â|ã|ä","a") .replaceAll("é|è|ê|ë","e"); }
public String isolarLink(String frase) {
String palavrasRetirar = "/-.pt-.com-.org-.com.br-.com.uk-https-::-//-http-.-:- ";
String[] palavrasChaveSeparadas = palavrasRetirar.split("-");
for (int x = 0; x < palavrasChaveSeparadas.length; x++){
frase = frase.replace(palavrasChaveSeparadas[x], " ");
}
frase = frase.replaceAll("-"," ");
frase = frase.replaceAll(" "," ");
return frase;
}
public String removerSimbolos(String frase) {
String palavrasRetirar = "|-,-...- ";
String[] palavrasChaveSeparadas = palavrasRetirar.split("-");
for (int x = 0; x < palavrasChaveSeparadas.length; x++){
frase = frase.replace(palavrasChaveSeparadas[x], " ");
}
frase = frase.replace(" ", " ");
return frase;
}
public String removerAspasVirgulas(String frase) {
frase = frase.replaceAll("\""," ");
frase = frase.replaceAll(","," ");
frase = frase.replaceAll(" ", " ");
return frase;
}
public Resultados searchGoogle(String searchQuery) throws IOException {
Resultados result = new Resultados();
// lets get the top results counting to nearly 15
String request = "https://www.google.com/search?q=" + searchQuery + "&num=10elton ";
Document doc = Jsoup.connect(request)
.userAgent("Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)").get();
// get the required content from response . Here ( h3 a ) is the selector
// pattern for selecting all heading links
// System.out.println( "--> \n" + doc.toString() );
Elements links = doc.select(".kCrYT");
for (Element link : links) {
Elements el_a = link.select("a");
String hrefValue = el_a.attr("href");
Elements el_divs = el_a.select("div");
String nome = "";
if(el_divs.size() > 0) {
nome = (String) el_divs.get(0).html();
}
if (hrefValue.startsWith("/url?q=")) {
try {
String slink = extractLink(hrefValue);
if( slink != null ) {
hrefValue = URLDecoder.decode(slink, StandardCharsets.UTF_8.toString());
result.setTitulo(nome);
result.setURL(hrefValue);
}
} catch (UnsupportedEncodingException ex) {
throw new RuntimeException(ex.getCause());
} catch(java.lang.IndexOutOfBoundsException ie) {
ie.printStackTrace();
}
}
}
return result;
}
// extract required titulosResultados from href value
private static String extractLink(String href) {
String result = null;
Matcher m = p.matcher(href);
if (m.find()) {
result = m.group();
}
return result;
}
private boolean isEmpty(Resultados news) {
if (news.getTitulo().isEmpty()) return true;
if (news.getURL().isEmpty()) return true;
return false;
}
}
Classe Resultados:
package com.newschecker.demochecker.domain;
import java.io.Serializable;
@SuppressWarnings("serial")
public class Resultados implements Serializable {
private String titulo;
private String url;
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getURL() {
return url;
}
public void setURL(String url) {
this.url = url;
}
public String toString() {
return "Titulo: "+ titulo + " Site: "+ url;
}
}