我有一个关于Instagram API和速率限制的问题 - 以及如何通过访问令牌循环来解决这个问题。Python Instagram API - 如何通过访问令牌循环访问速率限制?
此前,我使用统计软件程序构建了一个API接口来提取数据并进行手动解析。这是在我意识到Python-Instagram包容易得多之前。
问题:这就是说,我能够创建一个循环,在达到速率限制时,它将释放当前的访问令牌,并循环访问令牌列表,直到它遇到未使用的请求,然后继续通过提取。我使用此功能为特定用户提供了关注者列表,该用户拥有超过100万的关注者。使用Python Instagram API接口,我有麻烦重新创建它。
这里的起始码(从python-instagram):
详尽EXTRACT的追随者清单给定用户:
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:
声明捕获,并且循环W¯¯不正确的循环访问令牌 - 但由于某种原因,这些不会被识别或“推回”Instagram API界面,并且数据不会被拉取。循环只是通过代码循环。
我知道这是可能的,因为我已经通过手动请求端点并在达到速率限制错误时切换访问令牌(使用其他软件包)来完成此操作,但我想要使用Python
Instagram API执行此操作。
我最初的想法是,continue
中断不会在适当的上游点重置循环,或者访问令牌无法在对user_followers, next_ = api.user_followed_by(userid)
端点的给定调用中“切换”。
非常好,这段代码简化了访问令牌循环并分散了用法!很好学习新的东西。 – user812783765