Google自定义搜索API - 搜索结果

时间:2016-05-22 20:49:04

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

自从谷歌从其更传统的搜索引擎api转向支持谷歌自定义搜索API后,我对自定义搜索引擎有些失落。我希望有人能够告诉我是否可以使用新框架实现(非常简单)目标,并且可能任何启动帮助都会很棒。

具体来说,我正在寻找一个程序,它将从文本文件中读取文本,然后在谷歌搜索中使用来自所述文档的五个单词 - 这一点是要弄清楚所述搜索会产生多少结果。

示例输入/输出将是:

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

输出:总共有7个结果

非常感谢,所有,感谢您的时间/帮助

2 个答案:

答案 0 :(得分:1)

首先,您需要在Google帐户中创建Google自定义搜索项目。 在此项目中,您必须获取自定义搜索引擎ID,称为cx参数。您还必须获取API密钥参数。这两项都可以从您的Google帐户中的Google自定义搜索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搜索返回的结果完全不同

答案 1 :(得分:0)

如果有人仍然需要一些CSE(谷歌自定义搜索引擎)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(即私有静态最终int HTTP_REQUEST_TIMEOUT = 3 * 600000;)