我一直试图使用Twitter API v2免费访问tweet,但我总是走进死胡同.这非常令人沮丧,因为我的代码没有像预期的那样工作.我一直收到属性错误的消息.我试着用谷歌搜索,但为这些代码片段提供的解决方案似乎不起作用,

以下是我收到的完整错误消息:

Traceback (most recent call last):
  File "filepath\twitter.py", line 21, in <module>
    class TweetStreamListener(tweepy.Stream):
AttributeError: module 'tweepy' has no attribute 'Stream'

如果任何人有使用Twitter API v2的经验,并且遇到过类似的问题,我们将非常感谢您的见解.提前感谢您的帮助!

import tweepy
import json
import csv
from kafka import KafkaProducer

api_key = 'x'
api_secret = 'y'
access_token = 'z'
access_token_secret = '&'

kafka_bootstrap_server = 'localhost:9092'
kafka_topic = 'twitter_data'

csv_output = 'filepath/twitter-data-from-api.csv'

kafka_producer = KafkaProducer(bootstrap_servers=kafka_bootstrap_server)

class TweetStreamListener(tweepy.Stream):
    def on_status(self, status):
        try:
            tweet_id = status.id
            tweet_text = status.text
            tweet_created = status.created_at.strftime('%Y-%m-%d %H:%M:%S')

            tweet_data = {
                'id': tweet_id,
                'text': tweet_text,
                'created at': tweet_created
            }

            kafka_producer.send(kafka_topic,
                                json.dumps(tweet_data).encode("UTF-8"),
                                api_version=(3, 5, 0))

            with open(csv_output, 'a', newline='', encoding='utf-8') as f:
                writer = csv.writer(f)
                writer.writerows([[tweet_id, tweet_text, tweet_created]])

        except Exception as e:
            print(f"Error: {str(e)}")

def extract_data():
    auth = tweepy.OAuthHandler(api_key, api_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)

    twitter_stream_listener = TweetStreamListener(api.auth, None)
    stream = tweepy.Stream(auth=api.auth, listener=twitter_stream_listener)

    stream.filter(['Key1', 'Key2', 'Key3'])

    kafka_producer.close()

extract_data()

推荐答案

根据这Tweepy份文件:

STREAM和AsyncStream在v4.13中已过时,并随一起删除 V4.14.

目前,你应该使用StreamingClient级或降级你的图书馆.

Python相关问答推荐

为什么判断pd.DataFrame的值与判断pd.Series的值存在差异(如果索引中有值)?

在Python中是否可以输入使用任意大小参数列表的第一个元素的函数

当测试字符串100%包含查询字符串时,为什么t fuzzywuzzy s Process.extractBests不给出100%分数?

Python中两个矩阵的自定义Hadamard风格产物

如何编写一个正规表达式来查找序列中具有2个或更多相同辅音的所有单词

如何匹配3D圆柱体的轴和半径?

数字梯度的意外值

Python plt.text中重叠,包adjust_text不起作用,如何修复?

如何在Python中使用时区夏令时获取任何给定本地时间的纪元值?

列表上值总和最多为K(以O(log n))的最大元素数

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

根据条件将新值添加到下面的行或下面新创建的行中

使用FASTCGI在IIS上运行Django频道

当多个值具有相同模式时返回空

时间序列分解

Python虚拟环境的轻量级使用

PyQt5,如何使每个对象的 colored颜色 不同?'

如何禁用FastAPI应用程序的Swagger UI autodoc中的application/json?

解决调用嵌入式函数的XSLT中表达式的语法移位/归约冲突

下三角形掩码与seaborn clustermap bug