【发布时间】:2016-08-31 01:04:30
【问题描述】:
注意:- 在参考堆栈溢出中的几个示例后,我已经编写了代码,但仍然无法获得所需的输出
我有一个 Python 脚本,其中循环使用 Instagram API 进行迭代。我将 user_id 作为 API 的输入,该 API 获得帖子数、关注者数和关注数。每次收到响应时,我都会将其加载到 JSON 模式中并附加到列表 data1、data2 和 data3。
问题是:= 某些帐户是私人帐户,不允许对其进行 API 调用。当我在 IDLE Python shell 中运行脚本时,它给出了错误
Traceback (most recent call last):
File "<pyshell#144>", line 18, in <module>
beta=json.load(url)
File "C:\Users\rnair\AppData\Local\Programs\Python\Python35\lib\site- packages\simplejson-3.8.2-py3.5-win-amd64.egg\simplejson\__init__.py", line 455, in load
return loads(fp.read(),
File "C:\Users\rnair\AppData\Local\Programs\Python\Python35\lib\tempfile.py", line 483, in func_wrapper
return func(*args, **kwargs)
**ValueError: read of closed file**
但 JSON 包含以下内容:-
{
"meta": {
"error_type": "APINotAllowedError",
"code": 400,
"error_message": "you cannot view this resource"
}
}
我的代码是:-
for r in range(307,601):
var=r,sheet.cell(row=r,column=2).value
xy=var[1]
ij=str(xy)
if xy=="Account Deleted":
data1.append('null')
data2.append('null')
data3.append('null')
continue
myopener=Myopen()
try:
url=myopener.open('https://api.instagram.com/v1/users/'+ij+'/?access_token=641567093.1fb234f.a0ffbe574e844e1c818145097050cf33')
except urllib.error.HTTPError as e: // I want the change here
data1.append('Private Account')
data2.append('Private Account')
data3.append('Private Account')
continue
beta=json.load(url)
item=beta['data']['counts']
data1.append(item['media'])
data2.append(item['followed_by'])
data3.append(item['follows'])
我使用的是 Python 版本 3.5.2。主要问题是 如果循环运行并且特定调用被阻塞并出现此错误,如何避免它并继续运行下一次迭代?另外,如果帐户是私人帐户,我想将“私人帐户”附加到列表中。
【问题讨论】:
标签: python json python-3.x for-loop error-handling