Tweepy (API V2) - 将响应转换为字典

问题描述 投票:0回答:2

我想在字典中获取 Twitter 帐户“POTUS”关注的人的信息。我的代码:

import tweepy, json

client = tweepy.Client(bearer_token=x)

id = client.get_user(username="POTUS").data.id

users = client.get_users_following(id=id, user_fields=['created_at','description','entities','id', 'location', 'name', 'pinned_tweet_id', 'profile_image_url','protected','public_metrics','url','username','verified','withheld'], expansions=['pinned_tweet_id'], max_results=13)

此查询返回类型“Response”,该类型又存储类型“User”:

Response(data=[<User id=7563792 name=U.S. Men's National Soccer Team username=USMNT>, <User id=1352064843432472578 name=White House COVID-19 Response Team username=WHCOVIDResponse>, <User id=1351302423273472012 name=Kate Bedingfield username=WHCommsDir>, <User id=1351293685493878786 name=Susan Rice username=AmbRice46>, ..., <User id=1323730225067339784 name=The White House username=WhiteHouse>], includes={}, errors=[], meta={'result_count': 13})

我尝试过

._json
.json()
,但都不起作用。

有谁知道如何将此响应转换为字典对象来使用? 预先感谢

python dictionary twitter tweepy twitter-api-v2
2个回答
0
投票

你可以做

previous_cursor, next_cursor = None, 0

while previous_cursor != next_cursor:
    followed_data = api.get_friend_ids(username = "POTUS", cursor = next_cursor)
    previous_cursor, next_cursor = next_cursor, followed_data["next_cursor"]
    followed_ids = followed_data["id"] #this is a list
    # do something with followed_ids like writing them to a file

获取关注帐户的用户 ID。

如果您想要用户名而不是 id,您可以使用

api.get_friends()
执行非常类似的操作,但这一次返回的项目较少,因此如果您打算关注这些帐户,使用 ids 可能会更快。


0
投票

找到解决方案了!将

return_type=dict
添加到客户端将返回所有内容作为字典!

client = tweepy.Client(bearer_token=x, return_type=dict)

但是,您必须更改线路才能获取用户 ID:

id = client.get_user(username="POTUS")['data']['id']
© www.soinside.com 2019 - 2024. All rights reserved.