python - 如何使用 Tweepy API 从推文中获取 media_url

标签 python twitter tweepy

我正在使用这段代码:

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/

相关文章:

python - 将数据从 jquery success 填充到模态时出现问题

python - 如何从 OpenCV "cv2.keypoint"对象中提取 x,y 坐标?

python - Tweepy - 使用推文字符串填充 pandas 数据框列时出现错误 144

http - Twitter API 返回 HTTP 429 - 请求过多

php - 从 twitter API 发送直接消息

api - Tweepy 流媒体和 Tweepy 搜索之间的区别

python - 使用 pip 安装 tweepy 模块

python - Windows 错误 0 "ERROR_SUCCESS"是什么意思?

python - 将属性添加到 Python 字典中的现有对象

Android - 共享