Ruby Google Custom Seach API get results from next

2019-07-31 16:41发布

the code below is only getting the results from the first page of the google pagination... how to get more results?

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条回答
Root(大扎)
2楼-- · 2019-07-31 17:37

Simply use the nextPageToken as a parameter in the next request until you get back a result without a nextPageToken key

next_page_token = body['nextPageToken']

response_page2 = client.execute(
  :api_method => search.cse.list,
  :parameters => {
    'nextPageToken' => next_page_token,
    'key' => 'xxxxxxxxxxxx',
    'cx' => 'xxxxxxxxxxxxxxxx'
  }
)
查看更多
登录 后发表回答