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

Twint output.tweets_list报'NoneType'不可下标错误求助

问题描述

我写了个简单程序,用来抓取指定Twitter用户的推文,逐词保存到.csv文件,同时用nltk做词性标注。但遍历twint.output.tweets_list时触发错误:twint.get:User:'NoneType' object is not subscriptable。我确认目标用户有推文,也排除了IP封锁的问题,代码和复现所需的nltk下载命令如下,求解决办法。

代码:

import twint
import csv
import nltk

# 配置Twint对象
c = twint.Config()
c.Username = "POTUS"
c.Limit = 100

# 运行Twint
twint.run.Search(c)

# 打开CSV文件,写入推文词语及其词性
with open('tweets_with_POS.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerow(["word", "part_of_speech"])
    for tweet in twint.output.tweets_list:
        words = nltk.word_tokenize(tweet.tweet)
        pos_tags = nltk.pos_tag(words)
        for word, pos in pos_tags:
            writer.writerow([word, pos])

复现需执行命令:

nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
解决方案

这个错误通常是因为Twint未正确将抓取结果存入tweets_list,或请求过程返回空数据,可尝试以下修复方式:

  • 开启对象存储配置:Twint默认不会把抓取结果存入tweets_list,需显式开启该配置。在Twint配置代码中添加c.Store_object = True:

    # 配置Twint对象
    c = twint.Config()
    c.Username = "POTUS"
    c.Limit = 100
    c.Store_object = True  # 新增此行,确保结果存入列表
    
  • 改用用户专属抓取方法:针对特定用户的推文抓取,twint.run.Profile比twint.run.Search更适配,替换原运行代码:

    # 运行Twint(替换原twint.run.Search(c))
    twint.run.Profile(c)
    
  • 降级Twint版本:新版本Twint可能存在API兼容问题,安装稳定旧版本:

    pip uninstall twint -y
    pip install twint==2.1.20
    
  • 添加延迟与空值校验:网络波动可能导致请求失败,添加延迟降低请求频率,同时在代码中增加空值校验避免报错:

    import time
    time.sleep(2)  # 延迟2秒再发起请求
    twint.run.Profile(c)
    
    # 写入CSV时增加空值判断
    with open('tweets_with_POS.csv', 'w', newline='', encoding='utf-8') as file:
        writer = csv.writer(file)
        writer.writerow(["word", "part_of_speech"])
        if twint.output.tweets_list:
            for tweet in twint.output.tweets_list:
                if tweet.tweet:
                    words = nltk.word_tokenize(tweet.tweet)
                    pos_tags = nltk.pos_tag(words)
                    for word, pos in pos_tags:
                        writer.writerow([word, pos])
        else:
            print("未抓取到任何推文")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 18:40:37