首页 > 解决方案 > Java Google 搜索程序不会打印搜索结果

问题描述

下面的程序,它的代码是在这里找到的(虽然我稍微编辑了它以包含一个 try-catch 块),应该执行谷歌搜索并将结果打印到屏幕上:

import java.io.IOException;
import java.util.Scanner;

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

public class GoogleSearchJava 
{

    public static final String GOOGLE_SEARCH_URL = "https://www.google.com/search";
    
    public static void main(String[] args) 
    {
        //Taking search term input from console
        Scanner scanner = new Scanner(System.in);
        System.out.println("Please enter the search term.");
        String searchTerm = scanner.nextLine();
        System.out.println("Please enter the number of results. Example: 5 10 20");
        int num = scanner.nextInt();
        scanner.close();

        String searchURL = GOOGLE_SEARCH_URL + "?q="+searchTerm+"&num="+num;
        //without proper User-Agent, we will get 403 error
        try
        {
            Document doc = Jsoup.connect(searchURL).userAgent("Mozilla/5.0").get();
            //below will print HTML data, save it to a file and open in browser to compare
            //System.out.println(doc.html());

            //If google search results HTML change the <h3 class="r" to <h3 class="r1"
            //we need to change below accordingly
            Elements results = doc.select("h3.r > a");

            for (Element result : results) 
            {
                    String linkHref = result.attr("href");
                    String linkText = result.text();
                    System.out.println("Text::" + linkText + ", URL::" + linkHref.substring(6, linkHref.indexOf("&")));
            }
        }
        catch(IOException e)
        {
            e.getStackTrace();
            System.out.println("ERROR");
        }   
    }
}

然而,在询问要显示的结果数量后,程序突然结束:

-------------------< com.mycompany:GoogleSearchJava >-------------------
Building GoogleSearchJava 1.0-SNAPSHOT
--------------------------------[ jar ]---------------------------------

--- exec-maven-plugin:1.5.0:exec (default-cli) @ GoogleSearchJava ---
Please enter the search term.
hello
Please enter the number of results. Example: 5 10 20
5
------------------------------------------------------------------------
BUILD SUCCESS
------------------------------------------------------------------------
Total time:  4.810 s
Finished at: 2021-09-18T00:51:59+02:00
------------------------------------------------------------------------

为什么程序不打印找到的结果?

标签: javaurlruntime

解决方案


推荐阅读