You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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:    无地理位置信息")

关键修改说明:

  1. 不再直接访问tweet.country_code或tweet.place,而是通过tweet.geo['place_id']获取关联的地点ID
  2. 利用place_map字典通过地点ID匹配对应的地点对象,从地点对象中提取country_code
  3. 增加多层判断逻辑,处理无geo信息、地点数据缺失等边缘情况,避免报错

内容的提问来源于stack exchange,提问作者dotdotdot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 14:11:13