自定义Google搜索API参数

时间:2015-02-20 10:06:17

标签: java google-search-api

我正在开发一个使用Google搜索特定域上特定关键字的应用程序。但是,抓取Google结果页面并从HTML解析结果并不是非常“干净”的方法,所以我切换到自定义Google搜索API。到目前为止,我设法获取单个关键字的结果,但是我无法获得多个关键字和多个域的结果。在自定义搜索的设置中,我将其设置为进行整个网络搜索,仅举几例。所以,我的问题是,如何在不在开发人员控制台中设置的情况下在特定域上搜索多个关键字?

提前致谢。

P.S。这是当前代码:

package org.wonderland.dev.java;

import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.model.Search;


public class GoogleSearchClient {

    final private String API_KEY = "AIzaSyDxxxxxxxxxxxxxxxxxx";
    final private String SEARCH_ENGINE_ID = "00844xxxxxxxxxx:xxxxxxxx";

    public void printResults() {
            String searchKeyWord = "app";       
            List<Result> resultList = this.getSearchResult(searchKeyWord);
            if(resultList != null && resultList.size() > 0){
                   for(Result result: resultList){
                      System.out.println(result.getTitle());
                    } 
            }
    }


    public List<Result> getSearchResult(String keyword){
        HttpTransport httpTransport = new NetHttpTransport();
        JsonFactory jsonFactory = new JacksonFactory();
        Customsearch customsearch = new Customsearch(httpTransport, jsonFactory,null);

        List<Result> resultList = null;
        try {
            Customsearch.Cse.List list = customsearch.cse().list(keyword);
            list.setKey(API_KEY);
            list.setCx(SEARCH_ENGINE_ID);
            list.setNum(10L);
            Search results = list.execute();
            resultList = results.getItems(); 
        } catch (Exception e) {
            e.printStackTrace();
        }

        return resultList;
    }
}

0 个答案:

没有答案