【发布时间】:2015-10-25 08:46:12
【问题描述】:
我在查询 Twitter API 时遇到 404 和 401 错误,我的拉朋友的脚本由于未处理异常而中断。 已研究并尝试添加以下 try/except 规定,但未记录异常,并且 for 循环停止。
first = 0
last = 15
while last < len(list)+16: #while last group of 15 items is lower than number of items in list#
for item in list[first:last]: #parses twitter IDs in the list by groups of 15#
try:
results = twitter.friends.ids(skip_status="true",include_user_entities="false",count ="5000",user_id=item) #API query#
results = str(results)
text_file = open("output.txt", "a") #creates empty or opens current txt output / change path to desired output#
text_file.write(str(item) + "," + results + "\n") #adds twitter ID, resulting friends list, and a line skip to the txt output#
text_file.close()
break
except ValueError:
text_file = open("output.txt", "a") #creates empty or opens current txt output / change path to desired output#
text_file.write(str(item) + "," + "ERROR" + "\n") #adds twitter ID, resulting friends list, and a line skip to the txt output#
text_file.close()
print "Succesfully processed users " + str(list[first:last]) #returns recently processed group of 15 users#
first = first + 15 #updates list navigation to move on to next group of 15#
last = last + 15
time.sleep(1000) #suspends activities for 1000 seconds to respect rate limit#
还研究过基于 http 响应标头构建 if 语句,但我不明白如何插入 Python Twitter 工具“response.headers.get('h')”来做到这一点。处理和记录这些异常并让脚本继续提取数据的最佳方法是什么?
【问题讨论】:
-
你不想
break你在做什么! -
谢谢,已经删除了中断和“ValueError”,现在它可以正常工作,直到出现错误。然后该错误被正确记录,但 for 循环停止,而不是继续下一个.. 我正在阅读异常.. 我应该添加一个 else 语句来继续循环吗?
-
尝试在异常处理程序的最后一行之后添加
continue。 -
完美运行,谢谢!
标签: python api twitter error-handling exception-handling