0

I have used the jsoup for java but it retrieves very irrelevant links. Below is my code which I have used so far.

private static Pattern patternDomainName;
      private Matcher matcher;
      private static final String DOMAIN_NAME_PATTERN 
        = "([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}";
      static {
        patternDomainName = Pattern.compile(DOMAIN_NAME_PATTERN);
      } 
  public static void main(String[] args) {

    Scanner input = new Scanner(System.in);  
    FunnyCrawler obj = new FunnyCrawler();
    String str = input.nextLine();
    Set<String> result = obj.getDataFromGoogle(str);
    for(String temp : result){
        System.out.println(temp);
    }
    System.out.println(result.size());
  }

  public String getDomainName(String url){

    String domainName = "";
    matcher = patternDomainName.matcher(url);
    if (matcher.find()) {
        domainName = matcher.group(0).toLowerCase().trim();
    }
    return domainName;

  }

  private Set<String> getDataFromGoogle(String query) {

    Set<String> result = new HashSet<String>(); 
    String request = "https://www.google.com/search?q=" + query + "&num=20";
    System.out.println("Sending request..." + request);

    try {

        // need http protocol, set this as a Google bot agent :)
        Document doc = Jsoup
            .connect(request)
            .userAgent(
              "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)")
            .timeout(5000).get();

        // get all links
        Elements links = doc.select("a[href]");
        for (Element link : links) {

            String temp = link.attr("href");        
            if(temp.startsWith("/url?q=")){
                                //use regex to get domain name
                result.add(getDomainName(temp));
            }

        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;
  }

So, in java is there any other way to get the appropriate google search results which i normally get by using the google.com ? I'm working for jsp servlets so i need to run that code on servlet too....

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555

0 Answers0