python - 为什么状态“不可下标”,我该如何解决?Python Tweepy
问题描述
当有人用我的@handle 回复该推文时,我正在尝试使用我在下面制作的代码来获取推文中视频的媒体网址:
import tweepy
from tweepy import Stream
from tweepy.streaming import StreamListener
import json
class StdOutListener(StreamListener):
def on_data(self, data):
clean_data = json.loads(data)
tweetId = clean_data['id']
tweet_name = clean_data['user']['screen_name']
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
auth.set_access_token("access_token", "access_token_secret")
api = tweepy.API(auth)
mediaupload_id = clean_data['in_reply_to_status_id']
origtweet_media = api.get_status(mediaupload_id)
print()
print(origtweet_media)
native_media = origtweet_media['extended_entities']['media'][0]['video_info']
tweet_media = native_media['variants'][0]['url']
print(tweet_media)
def setUpAuth():
auth = tweepy.OAuthHandler("consumer_key", "consumer_secret")
auth.set_access_token("access_token", "access_token_secret")
api = tweepy.API(auth)
return api, auth
def followStream():
api, auth = setUpAuth()
listener = StdOutListener()
stream = Stream(auth, listener)
stream.filter(track=["@YOUR_TWITTER_HANDLE"], is_async=True)
if __name__ == "__main__":
followStream()
一切似乎都设置得很好,但是当我运行代码时,有人回复了一条带有视频的推文(回复的人提到了我的@handle),我收到了这个错误:
Exception has occurred: TypeError
'Status' object is not subscriptable
native_media = origtweet_media['extended_entities']['media'][0]['video_info']
为什么“状态”不可下标?有没有办法解决这个问题,所以它成功地抓取了视频 url ( tweet_media
)?
有人请帮助我!
解决方案
解决了!
仔细查看print
ed后origtweet_media
,我注意到推文信息在里面_json=()
。所以我添加._json
到末尾,origtweet_media = api.get_status(mediaupload_id)
因为它只是隔离了 json 部分,让我可以找到tweet_media
. 这是新更新的行的样子:
origtweet_media = api.get_status(mediaupload_id)._json
然后它成功了!
推荐阅读
- python - 将 logging.debug 保存在变量中或一一发送
- javascript - 解析一个数字,但将负数保留在文本框中
- html - 如何在使用 CSS 时为背景 URL 图像设置负边距?
- python - 类型检查通用数据类时出现不兼容的类型错误
- javascript - 在反应原生博览会中测量分贝
- elasticsearch - Kibana 7.14 | 日期格式 - 是否可以以 Epoch 格式存储日期,但在 Kibana 搜索查询中以 ISO 日期格式显示它
- node.js - 庆祝中间件快递 - NodeJS - 不适用于完整模式
- django - Django-CMS 将内容添加到第一页
- regex - 正则表达式匹配字符串,除了最后四个字符和回车换行符
- javascript - 通过 Mongoose & Express 接受表单中的数据并将其保存到 MongoDB