使用Instagram gem获取所有用户的图片

我想使用instagram gem( https://github.com/Instagram/instagram-ruby-gem )获取我的所有图片,但我无法了解具体方法。

这是我到目前为止所尝试的:

client = Instagram.client(access_token: token) client.user_recent_media.each do |media| puts media.images.thumbnail.url end 

它显然有效(那些是我的Instagram图像),但我无法取得所有这些或以任何方式选择我想从Instagram获得哪些内容。

例如,我看到方法user_recent_media接受一个“count”属性,应该让我使用某种分页:

 (from https://github.com/Instagram/instagram-ruby-gem/blob/master/lib/instagram/client/users.rb#L150) @option options [Integer] :count (nil) Limits the number of results returned per page 

不幸的是,我不知道这个分页应该如何工作。 例如,如果我请求1000个媒体元素(只是说所有这些元素)它不起作用并返回更少的元素,那时我被卡住了因为我不知道如何请求第2页

有没有人使用Instagramgem这样的东西? 任何帮助是极大的赞赏

下面是来自导入用户的旧应用程序的function代码(我只使用1.1.5 Instagram Gem运行它仍然有效),它也使用了光标。 您应该能够更改一些变量和行并继续前进:

  def import_followers response = user.client.user_follows followers = [].concat(response) next_cursor = response.pagination[:next_cursor] while !(next_cursor.to_s.empty?) do response = Instagram.user_follows(uid, {:cursor => next_cursor}) next_cursor = response.pagination[:next_cursor] followers.concat(response) end return followers end 

基于@nrowegt的答案,我定制了代码。

首先,我们初始化Instagram Gem(访问令牌将映射Instagram用户ID)

 client = Instagram.client(:access_token => session[:access_token]) 

然后,我们将运行user_recent_media方法并将响应保存在变量中

 response = client.user_recent_media 

我们需要创建一个空数组来保存所有图片并添加我们的响应。 请记住,Instagram API每次调用只返回20个项目,这就是我们需要执行数组和下面“while”的原因。

 album = [].concat(response) 

如果用户有更多图片,则响应变量将具有名为next_max_id的变量。 这是在分页方法内; 所以我们将next_max_id存储在一个变量上。

 max_id = response.pagination.next_max_id 

这是棘手的部分。 当max_id变量存在时,您需要运行上面的代码。 如果我们到达用户图片的最后一页,它将是空的。 所以:

 while !(max_id.to_s.empty?) do response = client.user_recent_media(:max_id => max_id) max_id = response.pagination.next_max_id album.concat(response) end 

只有这一点我们运行user_recent_media方法传递max_id变量,因此Instagram可以找出从哪里开始获取图片。

然后我们将最终变量发送到视图

 @album = album 

这是完整的代码。

 client = Instagram.client(:access_token => session[:access_token]) response = client.user_recent_media album = [].concat(response) max_id = response.pagination.next_max_id while !(max_id.to_s.empty?) do response = client.user_recent_media(:max_id => max_id) max_id = response.pagination.next_max_id album.concat(response) end @album = album 

根据文档,您应该在API中收到的任何响应中收到pagination哈希值。 类似下面的内容(取自文档):

 { ... "pagination": { "next_url": "https://api.instagram.com/v1/tags/puppy/media/recent?access_token=fb2e77d.47a0479900504cb3ab4a1f626d174d2d&max_id=13872296", "next_max_id": "13872296" } } 

您必须从next_url属性调用URL以检索下一组数据。

所以,我猜你应该能够检索如下:

 client.user_recent_media.pagination.next_url