以下代碼取自:Java code for using google custom search API。它能正確地提取Google搜索結果頁面中第一頁的前10個結果。谷歌自定義搜索API,如何使用Java以編程方式遍歷谷歌結果頁?
public static void main(String[] args) throws Exception {
String key="YOUR KEY";
String qry="Android";
URL url = new URL("https://www.googleapis.com/customsearch/v1?
key="+key+ "&cx=013036536707430787589:_pqjad5hr1a&q="+ qry + "&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br =
new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null)
{
if(output.contains("\"link\": \""))
{
String link=output.substring(output.indexOf("\"link\": \"")+
("\"link\": \"").length(), output.indexOf("\","));
System.out.println(link); //Will print the google search links
}
}
conn.disconnect();
}
我想弄清楚如何遍歷所有結果頁?通過搜索https://developers.google.com/custom-search/v1/using_rest我發現查詢中的start
參數反映了索引,很顯然,通過在循環中更改此值可以達到目的,但會花費我對每個頁面的查詢(這不應該是這種情況,因爲它不是一個新的查詢,它是相同的查詢,但只是新的頁面)。此外,我發現谷歌已經提到,如果查詢成功,響應數據包含值爲totalResults
的總體結果,但他們提到它是估計數。那麼,如何才能獲得這項服務的好處並獲得實際的結果數量或頁面數量以便遍歷它們?我沒有任何意義,我發出每個頁面的新查詢。
@Pargat:檢查這個問題plz。 –