【发布时间】:2016-06-25 20:49:48
【问题描述】:
我有一个关于 Instagram API 和速率限制的问题 - 以及如何循环访问令牌来解决这个问题。
之前,我使用统计软件程序构建了一个 API 接口来提取数据并手动解析。这是在我意识到 Python-Instagram 包要简单得多之前。
问题:话虽如此,我能够创建一个循环,在达到速率限制时,它将释放当前访问令牌并循环访问访问令牌列表,直到它遇到未使用的请求,然后继续通过提取。我正在使用它来为给定用户提取关注者列表,该用户拥有超过 100 万关注者。使用 Python Instagram API 接口,我无法重新创建它。
这是起始代码(来自python-instagram):
详尽地为给定用户提取关注者列表:
user_followers, next_ = api.user_followed_by(userid) #request data from API
while next_:
more_user_followers, next_ = api.user_followed_by(with_next_url=next_) #extract the list of followers
user_followers.extend(more_user_followers) #append each page of followers into this list with each iteration
这是我创建访问令牌循环直到未使用的令牌循环的尝试:
counter=0 #set seed counter
user_followers, next_ = api.user_followed_by(userid) #request data from API
while next_:
try:
more_user_followers, next_ = api.user_followed_by(with_next_url=next_) #extract the list of followers and capture any error codes
except InstagramAPIError:
counter=counter+1 #upon rate-limit error, increment counter by 1 to call each access token
if counter==1:
access_token="accesstoken1"
if counter==2:
access_token="accesstoken2"
# etc...
counter=0 #for the final access_token in the list, reset counter to 0 to re-start at the top of the list and cycle until a hit is found
api=InstagramAPI(access_token=access_token,client_secret=client_secret) #I think this should push the new access_token to the Instagram API constructor, but perhaps this is where the error lies...
continue #I think this will break the current cycle and restart under the `while next_:` statement, thus attempting to pull the data using the new access token
user_followers.extend(more_user_followers) #append each page of followers into this list with each iteration
使用try: 语句成功捕获了速率限制错误,并且循环将正确循环访问令牌 - 但由于某种原因,这些令牌不会被识别或“推送”回 Instagram API 接口和数据不会被拉取。循环只是不断循环代码。
我知道这是可能的,因为我已经通过手动请求端点并在遇到速率限制错误时切换访问令牌来完成此操作(使用另一个软件包),但我想使用 Python Instagram API 来做到这一点.
我最初的想法是 continue 中断不会在适当的上游点重置循环,或者访问令牌不能在给定的 user_followers, next_ = api.user_followed_by(userid) 端点调用中“切换出去”。
【问题讨论】:
标签: python api loops instagram access-token