我有一个与此问题类似的问题(Problem with getting user.fields from Twitter API 2.0)\n但我正在使用 Tweepy。当使用 tweet_fields 发出请求时,响应仅给我默认值。在我使用 user_fields 的另一个功能中,它工作得很好。 \n我遵循了本指南,特别是第 17 号(https://dev.to/twitterdev/a-compressive-guide-for-using-the-twitter-api-v2-using -tweepy-in-python-15d9 )
\n我的函数如下所示:
\ndef get_user_tweets():\n client = get_client()\n tweets = client.get_users_tweets(id=get_user_id(), max_results=5)\n ids = []\n for tweet in tweets.data:\n ids.append(str(tweet.id))\n\n tweets_info = client.get_tweets(ids=ids, tweet_fields=["public_metrics"])\n print(tweets_info)\nRun Code Online (Sandbox Code Playgroud)\n这是我的回复(来自 elonmusk 的最后一条推文),也没有错误代码或其他任何内容
\nResponse(data=[<Tweet id=1471419792770973699 text=@WholeMarsBlog I came to the US with no money & graduated with over $100k in debt, despite scholarships & working 2 jobs while at school>, <Tweet id=1471399837753135108 text=@TeslaOwnersEBay @PPathole @ScottAdamsSays @johniadarola @SenWarren It\xe2\x80\x99s 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 \xe2\x9d\xa4\xef\xb8\x8f>], includes={}, errors=[], meta={})\nRun Code Online (Sandbox Code Playgroud)\n
小智 8
我找到了这个链接: https: //giters.com/tweepy/tweepy/issues/1670。据其介绍,
响应是一个命名元组。这里,在其数据字段中,有一个 Tweet 对象。
Tweet 对象的字符串表示形式将仅包含其 ID 和文本。这是一个有意的设计选择,以减少在将所有数据打印为字符串表示形式时可能显示的过多信息,就像 models.Status 一样。ID 和文本是唯一的默认/保证字段,因此字符串表示形式保持一致和唯一,同时仍然简洁。此设计在整个 API v2 模型中使用。
要访问 Tweet 对象的数据,您可以使用属性或键(如字典)来访问每个字段。如果您希望将所有数据作为字典,则可以使用 data 属性/键。
在这种情况下,要访问公共指标,您可以尝试这样做:
tweets_info = client.get_tweets(ids=ids, tweet_fields=["public_metrics"])
for tweet in tweets_info.data:
print(tweet["id"])
print(tweet["public_metrics"])
Run Code Online (Sandbox Code Playgroud)