我正在使用这段代码:
import tweepy
from tweepy.api import API
import urllib
import os
i = 1
consumer_key="xx"
consumer_secret="xx"
access_token="xx"
access_token_secret="xx"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)
class MyStreamListener(tweepy.StreamListener):
def __init__(self, api=None):
self.api = api or API()
self.n = 0
self.m = 10
def on_status(self, status):
if 'media' in status.entities:
for image in status.entities['media']:
global i
#picName = status.user.screen_name
picName = "pic%s.jpg" % i
i += 1
link = image['media_url']
filename = os.path.join("C:/Users/Charbo/Documents/Python/",picName)
urllib.urlretrieve(link,filename)
#use to test
print(status.user.screen_name)
else:
print("no media_url")
self.n = self.n+1
if self.n < self.m:
return True
else:
print ('tweets = '+str(self.n))
return False
def on_error(self, status):
print (status)
myStreamListener = MyStreamListener()
myStream = tweepy.Stream(auth, MyStreamListener(),timeout=30)
myStream.filter(track=['#feelthebern'])
我正在尝试访问我字典中“照片”下的 media_url。但我收到以下错误:'dict' 对象没有属性 'media'。如果能帮助我浏览 JSON,我将不胜感激。
提前致谢!
最佳答案
你应该尝试两件事:
- 将实体添加到您的请求中
>
tweepy.Cursor(api.search, q="#hashtag", count=5, include_entities=True)
- 检查媒体是否不为空:
>
if 'media' in tweet.entities:
for image in tweet.entities['media']:
(do smthing with image['media_url'])
希望对你有帮助
关于python - 如何使用 Tweepy API 从推文中获取 media_url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36710850/