繁体   English   中英

为什么我在以下 python 代码中收到 KeyError?

[英]Why am I getting KeyError in the following python code?

我想执行这段代码。

这是运行代码后我在终端中遇到的错误

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 :)'

这意味着您在响应 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

 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM