我使用以下代码查询Facebook,迭代页面名称列表以获取页面的数字ID并将其存储在字典中。然而,我继续追赶HTTP 500 error
;但是,这并没有出现在我在这里提供的短名单中。见代码:
import json
def FB_IDs(page_name, access_token=access_token):
""" get page's numeric information """
# construct URL
base = "https://graph.facebook.com/v2.4"
node = "/" + str(page_name)
parameters = "/?access_token=%s" % access_token
url = base + node + parameters
# retrieve data
with urllib.request.urlopen(url) as url:
data = json.loads(url.read().decode())
return data
pages_ids_dict = {}
for page in pages:
pages_ids_dict[page] = FacebookIDs(page, access_token)['id']
如何自动执行此操作并避免错误?
答案 0 :(得分:0)
有一个非常标准的辅助函数,您可能需要查看它:
### HELPER FUNCTION ###
def request_until_succeed(url):
""" helper function to catch HTTP error 500"""
req = urllib.request.Request(url)
success = False
while success is False:
try:
response = urllib.request.urlopen(req)
if response.getcode() == 200:
success = True
except Exception as e:
print(e)
time.sleep(5)
print("Error for URL") # use following code if URL shall be printed %s: %s" % (url, datetime.datetime.now()))
return response.read()
将该功能实现到您的功能中,以便您的函数通过该函数调用URL,您应该没问题。