使用Tweepy获取推文country_code触发AttributeError问题解决
如何通过Tweepy获取推文的国家代码?
你遇到的问题根源是:推文对象本身并不直接包含country_code或place属性,国家代码这类地理位置信息是通过API的expansions参数关联到响应的includes.places部分的,需要通过推文的geo.place_id去匹配对应的地点数据。
以下是修正后的完整代码,可正确获取国家代码:
import tweepy bt = "..." client = tweepy.Client(bearer_token=bt) query = 'hello has:geo -is:retweet' response = client.search_all_tweets( query=query, tweet_fields=['geo'], place_fields=['country_code'], expansions=['geo.place_id'], max_results=10 ) tweets = response.data # 处理可能不存在places的情况,避免空引用报错 places = response.get('includes', {}).get('places', []) # 构建地点ID到地点对象的映射字典 place_map = {place.id: place for place in places} for tweet in tweets: print(tweet.id) print(tweet.text) # 逐层判断,避免无地理位置信息时的报错 if tweet.geo and 'place_id' in tweet.geo: place_id = tweet.geo['place_id'] target_place = place_map.get(place_id) if target_place: print(" country: ", target_place.country_code) else: print(" country: 未找到对应地点数据") else: print(" country: 无地理位置信息")
关键修改说明:
- 不再直接访问
tweet.country_code或tweet.place,而是通过tweet.geo['place_id']获取关联的地点ID - 利用
place_map字典通过地点ID匹配对应的地点对象,从地点对象中提取country_code - 增加多层判断逻辑,处理无geo信息、地点数据缺失等边缘情况,避免报错
内容的提问来源于stack exchange,提问作者dotdotdot
相关产品推荐
相关产品推荐

