无法控制 api json 格式、文本或视频结果?


CONSUMER_KEY = "*******"
CONSUMER_SECRET = "***"
ACCESS_KEY = "**"
ACCESS_SECRET = ****"
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
requests.get(url, auth=auth)    

r = requests.get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=coderFord&count=2',auth=auth)
res=r.json()

def id_al(): 
for item in res:
b=item['id']
print(b)
req_ya(b)

def req_ya(b):
params = {"ids": b}         
ponse = requests.get("https://api.twitter.com/labs/1/tweets/metrics/private", params=params,auth=auth)
ak=ponse.json()
for itema in ak['data']:
for items in res:    
k=itema['tweet'] 
p=itema['video']
data = {"created_at":items['created_at'],"text":items['text'],"tweet_id": itema['tweet_id'], "like_count": k['like_count'],"retweet_count": k['retweet_count'],"quote_count": k['quote_count'],"reply_count": k['reply_count'],"impression_count": k['impression_count'],"view_count":p['view_count']}
data_dict = json.dumps(data, indent = 4, sort_keys = True)
print(json.loads(data_dict))
collection.insert_one(data)
print(id_al())

错误: 键错误:"视频">

如果我发送的推文是文本,则不会向我发送视频视图。它给出了一个错误。我该如何控制它

而且我无法检查,因为推文的类型部分不存在。

像这样的响应示例

https://developer.twitter.com/en/docs/labs/tweet-metrics/quick-start/get-tweets-metrics-private

您可以先检查是否存在'video' in itema.keys(),然后在此条件下执行逻辑。

替换此部分,

for itema in ak['data']:
for items in res:    
k=itema['tweet'] 
p=itema['video'] # here you are getting error.

for itema in ak['data']:
for items in res:    
k=itema['tweet'] 
if 'video' in itema.keys():
p = itema['video'] 

相关内容

  • 没有找到相关文章

最新更新