我想执行此代码。
这是我在运行代码
后进入终端的错误Traceback (most recent call last):
File "/private/var/folders/6j/n37bd5r92sj8wfkn3k_k9k580000gp/T/Cleanup At Startup/bday-459934533.707.py", line 68, in <module>
print 'total='+str(process_posts(url))
File "/private/var/folders/6j/n37bd5r92sj8wfkn3k_k9k580000gp/T/Cleanup At Startup/bday-459934533.707.py", line 32, in process_posts
posts=res_obj["data"]
KeyError: 'data'
代码是 -
import httplib, urllib
from bs4 import BeautifulSoup
import os
import json
import time
import calendar
access_token='value'
dob='2015-07-30'
conn = httplib.HTTPSConnection("graph.facebook.com")
print 'requesting...'
#conn.request("GET",path,urllib.urlencode(data),{})
has_more=False
def convert_to_local(s):
t=time.strptime(s[:19],"%Y-%m-%dT%H:%M:%S")
t=time.localtime(calendar.timegm(t))
t=time.strftime("%Y-%m-%d",t)
return t
def getRandomThnx(msg):
return 'thanks :)'
def process_posts(url):
conn = httplib.HTTPSConnection("graph.facebook.com")
conn.request("GET",url)
res = conn.getresponse()
conn.getresponse
data=res.read()
res_obj=json.loads(data)
posts=res_obj["data"]
processed=0
for post in posts:
if not "message" in post:
continue
msg=post["message"]
post_date=convert_to_local(post["created_time"])
if dob == post_date:
if "from" in post and "message" in post:
user= post["from"]["name"]
path='/'+post['id']+'/comments'
param_data={ 'format':'json',
'message':getRandomThnx(msg),
'access_token':access_token
}
conn = httplib.HTTPSConnection("graph.facebook.com")
if post["comments"]["count"]==0:
print 'responding to :'+user+'->'+msg
conn.request("POST",path,urllib.urlencode(param_data),{})
res = conn.getresponse()
path='/'+post['id']+'/likes'
param_data={ 'format':'json',
'access_token':access_token
}
conn = httplib.HTTPSConnection("graph.facebook.com")
processed+=1
if "paging" in res_obj:
return processed+process_posts(res_obj["paging"]["next"] [len("https://graph.facebook.com"):])
else:
print "Finished"
return processed
url='/me/feed?access_token='+access_token
print 'total='+str(process_posts(url))
print 'Thanx to all wisher :)'
答案 0 :(得分:0)
这意味着您收到的响应GET查询的data
json不包含“数据”键。
您可以通过执行以下操作来可视化json数据的样子:
import httplib, urllib
from bs4 import BeautifulSoup
import os
import json
import time
import calendar
access_token='value'
dob='2015-07-30'
conn = httplib.HTTPSConnection("graph.facebook.com")
print 'requesting...'
#conn.request("GET",path,urllib.urlencode(data),{})
has_more=False
def convert_to_local(s):
t=time.strptime(s[:19],"%Y-%m-%dT%H:%M:%S")
t=time.localtime(calendar.timegm(t))
t=time.strftime("%Y-%m-%d",t)
return t
def getRandomThnx(msg):
return 'thanks :)'
def process_posts(url):
conn = httplib.HTTPSConnection("graph.facebook.com")
conn.request("GET",url)
res = conn.getresponse()
conn.getresponse
data=res.read()
res_obj=json.loads(data)
try:
posts=res_obj["data"]
except:
print "res_obj does not contain 'data', here is what res_obj looks like:"
print data
...