【问题标题】:Python Twitter Filter and Collecting TweetsPython Twitter 过滤器和收集推文
【发布时间】:2021-10-26 05:50:46
【问题描述】:

我现在正在从事自然语言处理项目,但我一开始就无法收集特定语言的推文。

我正在尝试将 tweepy 库与 python 一起使用,但此代码在控制台上没有任何回报

我哪里做错了?

from tweepy import Stream
from tweepy import OAuthHandler
from tweepy.streaming import StreamListener
import time
import json

# authentication data- get this info from twitter after you create your application
ckey="*****"
csecret="*****"
atoken="*****"
asecret="*****"

# define listener class
class listener(StreamListener):

    def on_data(self, data):
        try:
            print (data)   # write the whole tweet to terminal
            return True
        except BaseException as e:
            print('failed on data, ', str(e)) # if there is an error, show what it is
            time.sleep(5)  # one error could be that you're rate-limited; this will cause the script to pause for 5 seconds

    def on_error(self, status):
        print (status)

# authenticate yourself
auth = OAuthHandler(ckey, csecret)
auth.set_access_token(atoken, asecret)
twitterStream = Stream(auth, listener())
twitterStream.filter(languages=['tr'])  # track what you want to search for!

【问题讨论】:

  • 作为建议,即使它们是模拟密钥,也不要在线发布密钥,因为有人可能会通过使用这些密钥来冒充您

标签: python api twitter tweepy


【解决方案1】:

我运行了您的代码并收到了一个 406 错误,根据 API 这意味着查询不是可接受的请求。在过滤器方法中添加跟踪项参数后,它可以正常工作。我相信这是 API 本身的限制。另见406 error in Streaming API when filtering on language

【讨论】:

  • 即使使用 track 参数,它也没有从请求中打印任何结果,仍然不知道如何打印
  • 首先我会从您最初的问题中删除您的 API 密钥。其次,我使用我的凭据运行了您的代码,并且运行良好。是否为您打印任何错误代码?
  • 它甚至没有给出任何响应,即使有跟踪参数。它只是工作,甚至没有调试。
  • 尝试生成新的 API 密钥。
【解决方案2】:

例如,我想搜索 10000 条包含单词“#tennis”的推文并打印推文文本和作者

api = tweepy.API(auth)
TestTweet = tweepy.Cursor(api.search, q="#tennis").items(10000)

while True:
  try:
      tweet = TestTweet.next()
      print(str(tweet.author.screen_name))
      print(tweet.text)

 except tweepy.error.TweepError:
      print "Twitter rate limit, need to wait 15 min"
      time.sleep(60 * 16)
      continue
 except StopIteration:
      break

如果你想按用户名搜索

tweet = api.get_status(id=user_name)
test_text = tweet.text
test_user = tweet.user.screen_name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-12
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2015-09-12
    • 2013-05-12
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多