Ruby Google Custom Search API从下一页获得结果

时间:2014-07-07 03:25:52

标签: ruby-on-rails ruby google-search google-custom-search

下面的代码只是从谷歌分页的第一页获得结果...如何获得更多结果?

require 'google/api_client'

# autenticação
client = Google::APIClient.new(:application_name => 'Ruby Drive sample',
      :application_version => '1.0.0', 
      :client_id => 'xxxxxxxxxxxxxxxx',
      :client_secret => 'xxxxxxxxxxxxxx',
      :authorization => nil)
search = client.discovered_api('customsearch')

# chama a API
response = client.execute(
  :api_method => search.cse.list,
    :parameters => {
      'q' => 'cafe',
      'key' => 'xxxxxxxxxxxx',
      'cx' => 'xxxxxxxxxxxxxxxx'
    }
)

# recebe a resposta em json
body = JSON.parse(response.body)
items = body['items']

# printa algumas informações...
items.each do |item|
  puts "#{item['formattedUrl']}"
end

1 个答案:

答案 0 :(得分:0)

只需在下一个请求中使用nextPageToken作为参数,直到您返回没有nextPageToken键的结果

next_page_token = body['nextPageToken']

response_page2 = client.execute(
  :api_method => search.cse.list,
  :parameters => {
    'nextPageToken' => next_page_token,
    'key' => 'xxxxxxxxxxxx',
    'cx' => 'xxxxxxxxxxxxxxxx'
  }
)