【问题标题】:Google Custom Search API - Search ResultsGoogle 自定义搜索 API - 搜索结果
【发布时间】:2025-03-06 09:15:04
【问题描述】:

自从 Google 从其更传统的搜索引擎 api 转而支持 google 自定义搜索 api 以来,我对自定义搜索引擎有点失去了联系。我希望有人能告诉我新框架是否可以实现(非常简单的)目标,并且任何开始的帮助都可能很棒。

具体来说,我希望编写一个程序,该程序将从文本文件中读取文本,然后在 google 搜索中使用所述文档中的五个单词 - 关键是要弄清楚所述搜索产生了多少结果。

输入/输出示例如下:

输入:“这是我的搜索词”——搜索中包含的引文!

输出:总共有 7 个结果

非常感谢大家的时间/帮助

【问题讨论】:

    标签: search search-engine google-custom-search


    【解决方案1】:

    首先,您需要在您的 Google 帐户中创建一个 Google 自定义搜索项目。 从这个项目中,您必须获得一个自定义搜索引擎 ID,称为 cx 参数。您还必须获取 API 密钥参数。这两个都可以从您的 Google 帐户中的 Google Custom Search API 项目中获得。

    然后,如果您更喜欢 Java,这里有一个工作示例:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    import java.net.HttpURLConnection;
    import java.net.URL;
    
    
    public class GoogleCustonSearchAPI {
    
    public static void main(String[] args) throws Exception {
    
    String key="your_key";
    String qry="your_query";
    String cx = "your_cx";
    
    //Fetch urls
    URL url = new URL(
    "https://www.googleapis.com/customsearch/v1?key="+key+"&cx="+cx+"&q="+ qry +"&alt=json&queriefields=queries(request(totalResults))");
    
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "application/json");
    BufferedReader br = new BufferedReader(new InputStreamReader(
            (conn.getInputStream())));
    //Remove comments if you need to output in JSON format  
    /*String output;
    System.out.println("Output from Server .... \n");
    while ((output = br.readLine()) != null) {
        System.out.println(output);  
    }*/
    //Print the urls and domains from Google Custom Search                                                                               String searchResult;        
        while ((searchResult = output.readLine()) != null) {  
            int startPos=searchResult.indexOf("\"link\": \"")+("\"link\": \"").length();
            int endPos=searchResult.indexOf("\",");
            if(searchResult.contains("\"link\": \"") && (endPos>startPos)){ 
                String link=searchResult.substring(startPos,endPos);
                if(link.contains(",")){
                    String tempLink = "\"";
                    tempLink+=link;
                    tempLink+="\"";
                    System.out.println(tempLink);
                }
                else{
                   System.out.println(link);                
                }
                System.out.println(getDomainName(link));
            }     
        } 
    conn.disconnect();                
    }
    
    public static String getDomainName(String url) throws URISyntaxException {
        URI uri = new URI(url);
        String domain = uri.getHost();
        return domain.startsWith("www.") ? domain.substring(4) : domain;
    }
    

    “&queriefields=queries(request(totalResults))”是与众不同的地方,它可以满足您的需求。但请记住,您每天只能免费执行 100 次查询,而且自定义搜索 API 的结果有时与 Google.com 搜索返回的结果大不相同

    【讨论】:

    • 在这里您可以找到 cx id:google.com/cse/manage/all。然后查找“我的搜索引擎”,然后从列表中进行选择。当您选择您的引擎时,详细信息右侧有一个“搜索引擎 ID”按钮。这是cx。希望我能帮上忙!
    • 这很有帮助。但我有一个问题。我想知道谷歌为任何随机查询返回的结果。由于 Googled 杀死了 ajax api,我正在尝试使用 CSE。但我不知道如何使用它。我选择 Google.com 来创建自定义搜索引擎,但它会返回来自 Google 服务的结果。我应该如何制作一个显示谷歌结果的自定义搜索引擎?
    • 我找到了方法。通过修改basics 选项卡并选择search entire web。但是您知道阅读JSON objects 的好文档吗?
    • 您可以找到多种使用 Java 在 Web 上读取 json 对象的方法。这是一个链接:examples.javacodegeeks.com/core-java/json/…。如果您认为我对您有所帮助,请您将我的回答视为您问题的解决方案并点赞?
    • 当然,我正在考虑支持您的回答。但它缺乏 JASON 操纵。
    【解决方案2】:

    如果有人仍然需要一些 CSE(Google 自定义搜索引擎)API 示例,这是工作方法

    public static List<Result> search(String keyword){
        Customsearch customsearch= null;
    
    
        try {
            customsearch = new Customsearch(new NetHttpTransport(),new JacksonFactory(), new HttpRequestInitializer() {
                public void initialize(HttpRequest httpRequest) {
                    try {
                        // set connect and read timeouts
                        httpRequest.setConnectTimeout(HTTP_REQUEST_TIMEOUT);
                        httpRequest.setReadTimeout(HTTP_REQUEST_TIMEOUT);
    
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Result> resultList=null;
        try {
            Customsearch.Cse.List list=customsearch.cse().list(keyword);
            list.setKey(GOOGLE_API_KEY);
            list.setCx(SEARCH_ENGINE_ID);
            Search results=list.execute();
            resultList=results.getItems();
        }
        catch (  Exception e) {
            e.printStackTrace();
        }
        return resultList;
    }
    

    此方法返回结果对象列表,因此您可以对其进行迭代

        List<Result> results = new ArrayList<>();
    
        try {
            results = search(QUERY);
        } catch (Exception e) {
            e.printStackTrace();
        }
        for(Result result : results){
            System.out.println(result.getDisplayLink());
            System.out.println(result.getTitle());
            // all attributes
            System.out.println(result.toString());
        }
    

    我使用 gradle 依赖项

    dependencies {
    compile 'com.google.apis:google-api-services-customsearch:v1-rev57-1.23.0'
    }
    

    别忘了定义自己的GOOGLE_API_KEY、SEARCH_ENGINE_ID (cx)、QUERY和HTTP_REQUEST_TIMEOUT(即private static final int HTTP_REQUEST_TIMEOUT = 3 * 600000;)

    【讨论】: