使用Python从Twitter获取带有标签的tweets

2024-04-25 19:26:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我们如何根据散列标签查找或获取tweets。i、 我想找到关于某个主题的tweets?在Python中可以使用Twython吗?

谢谢


Tags: 主题标签tweetstwython
1条回答
网友
1楼 · 发布于 2024-04-25 19:26:26

编辑 我最初使用Twython的hooks作为搜索API的解决方案似乎不再有效,因为Twitter现在希望用户通过身份验证才能使用搜索。要通过Twython执行经过身份验证的搜索,只需在初始化Twython对象时提供Twitter身份验证凭据。下面,我将粘贴一个如何实现这一点的示例,但是您需要查阅Twitter API文档中的GET/search/tweets,以了解可以在搜索中分配的不同可选参数(例如,页面浏览结果、设置日期范围等)

from twython import Twython

TWITTER_APP_KEY = 'xxxxxx'  #supply the appropriate value
TWITTER_APP_KEY_SECRET = 'xxxxxx' 
TWITTER_ACCESS_TOKEN = 'xxxxxxx'
TWITTER_ACCESS_TOKEN_SECRET = 'xxxxxx'

t = Twython(app_key=TWITTER_APP_KEY, 
            app_secret=TWITTER_APP_KEY_SECRET, 
            oauth_token=TWITTER_ACCESS_TOKEN, 
            oauth_token_secret=TWITTER_ACCESS_TOKEN_SECRET)

search = t.search(q='#omg',   #**supply whatever query you want here**
                  count=100)

tweets = search['statuses']

for tweet in tweets:
  print tweet['id_str'], '\n', tweet['text'], '\n\n\n'

原始答案

here in the Twython documentation所示,您可以使用Twython访问Twitter搜索API:

from twython import Twython
twitter = Twython()
search_results = twitter.search(q="#somehashtag", rpp="50")

for tweet in search_results["results"]:
    print "Tweet from @%s Date: %s" % (tweet['from_user'].encode('utf-8'),tweet['created_at'])
    print tweet['text'].encode('utf-8'),"\n"

等等。。。请注意,对于任何给定的搜索,你可能最多会有2000条左右的tweets,最多会有一两个星期。您可以阅读更多关于Twitter搜索API here的信息。

相关问题 更多 >