【问题标题】:Problem with getting tweet_fields from Twitter API 2.0 using Tweepy使用 Tweepy 从 Twitter API 2.0 获取 tweet_fields 的问题
【发布时间】:2022-01-19 02:37:39
【问题描述】:

我有一个与这个问题类似的问题 (Problem with getting user.fields from Twitter API 2.0) 但我正在使用 Tweepy。当使用 tweet_fields 发出请求时,响应只会给我默认值。在我使用 user_fields 的另一个功能中,它可以完美运行。 我遵循了本指南,特别是第 17 号 (https://dev.to/twitterdev/a-comprehensive-guide-for-using-the-twitter-api-v2-using-tweepy-in-python-15d9)

我的函数如下所示:

def get_user_tweets():
    client = get_client()
    tweets = client.get_users_tweets(id=get_user_id(), max_results=5)
    ids = []
    for tweet in tweets.data:
        ids.append(str(tweet.id))

    tweets_info = client.get_tweets(ids=ids, tweet_fields=["public_metrics"])
    print(tweets_info)

这是我的回复(来自 elonmusk 的最后一条推文)也没有错误代码或其他任何内容

Response(data=[<Tweet id=1471419792770973699 text=@WholeMarsBlog I came to the US with no money &amp; graduated with over $100k in debt, despite scholarships &amp; working 2 jobs while at school>, <Tweet id=1471399837753135108 text=@TeslaOwnersEBay @PPathole @ScottAdamsSays @johniadarola @SenWarren It’s complicated, but hopefully out next quarter, along with Witcher. Lot of internal debate as to whether we should be putting effort towards generalized gaming emulation vs making individual games work well.>, <Tweet id=1471393851843792896 text=@PPathole @ScottAdamsSays @johniadarola @SenWarren Yeah!>, <Tweet id=1471338213549744130 text=link>, <Tweet id=1471325148435394566 text=@24_7TeslaNews @Tesla ❤️>], includes={}, errors=[], meta={})

【问题讨论】:

  • 注意缩进(方法声明后4个空格)。它打印什么?或者控制台上是否有任何错误 - 请分享这个。
  • 如果您遵循问题的答案会发生什么:将参数expansions = ['author_id'] 添加到get_tweets 的调用中?
  • 谢谢我编辑了我的问题。如果我添加 expands=["author_id"] 它只会给我有关用户的信息,但仍然不是公共指标。

标签: python tweepy


【解决方案1】:

我找到了这个链接:https://giters.com/tweepy/tweepy/issues/1670。据了解,

响应是一个命名元组。这里,在其数据字段中,是一个 Tweet 对象。

Tweet 对象的字符串表示将永远只包含其 ID 和文本。这是一个有意的设计选择,以减少在将所有数据打印为字符串表示形式时可能显示的过多信息,就像 models.Status 一样。 ID 和文本是唯一的默认/保证字段,因此字符串表示形式保持一致和唯一,同时仍然简洁。这种设计用于整个 API v2 模型。

要访问 Tweet 对象的数据,您可以使用属性或键(如字典)来访问每个字段。 如果要将所有数据作为字典,则可以使用数据属性/键。

在这种情况下,要访问公共指标,您可以尝试这样做:

tweets_info = client.get_tweets(ids=ids, tweet_fields=["public_metrics"])
for tweet in tweets_info.data:
    print(tweet["id"])
    print(tweet["public_metrics"])

【讨论】:

  • 谢谢!这有帮助:)
猜你喜欢
  • 2021-06-11
  • 2022-12-07
  • 2012-06-13
  • 2018-10-20
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
  • 2015-03-06
  • 2022-11-03
相关资源
最近更新 更多