easiest (legal) way to programmatically get the google search result count?

后端 未结 2 955
你的背包
你的背包 2020-12-31 18:52

I want to get the estimated result count for certain Google search engine queries (on the whole web) using Java code.

I need to do only very few queries per day, so

2条回答
  •  长发绾君心
    2020-12-31 18:57

    Well something you can do is perform an actual Google search programmatically to begin with. The easiest possible way to do this would be to access the url https://www.google.com/search?q=QUERY_HERE and then you want to scrape the result count off that page.

    Here is a quick example of how to do that:

        private static int getResultsCount(final String query) throws IOException {
        final URL url = new URL("https://www.google.com/search?q=" + URLEncoder.encode(query, "UTF-8"));
        final URLConnection connection = url.openConnection();
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        connection.addRequestProperty("User-Agent", "Mozilla/5.0");
        final Scanner reader = new Scanner(connection.getInputStream(), "UTF-8");
        while(reader.hasNextLine()){
            final String line = reader.nextLine();
            if(!line.contains("
    ")) continue; try{ return Integer.parseInt(line.split("
    ")[1].split("<")[0].replaceAll("[^\\d]", "")); }finally{ reader.close(); } } reader.close(); return 0; }

    For usage, you would do something like:

    final int count = getResultsCount("horses");
    System.out.println("Estimated number of results for horses: " + count);
    

提交回复
热议问题