使用 Python 从 Twitter 获取带有主题标签的推文

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14156625/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 10:37:50  来源:igfitidea点击:

Fetching tweets with hashtag from Twitter using Python

pythontwittertwython

提问by Uselesssss

How do we find or fetch tweets on the basis of hash tag. i.e. I want to find tweets regarding on a certain subject? Is it possible in Python using Twython?

我们如何根据哈希标签查找或获取推文。即我想找到关于某个主题的推文?是否可以在 Python 中使用 Twython?

Thanks

谢谢

采纳答案by Benjamin White

EDITMy original solution using Twython's hooks for the Search API appears to be no longer valid because Twitter now wants users authenticated for using Search. To do an authenticated search via Twython, just supply your Twitter authentication credentials when you initialize the Twython object. Below, I'm pasting an example of how you can do this, but you'll want to consult the Twitter API documentation for GET/search/tweetsto understand the different optional parameters you can assign in your searches (for instance, to page through results, set a date range, etc.)

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

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'


Original Answer

原答案

As indicated here in the Twython documentation, you can use Twython to access the Twitter Search API:

Twython 文档中所示,您可以使用 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"

etc... Note that for any given search, you're probably going to max out at around 2000 tweets at most, going back up to around a week or two. You can read more about the Twitter Search API here.

等等...请注意,对于任何给定的搜索,您可能最多会收到大约 2000 条推文,然后再回到大约一两个星期。您可以在此处阅读有关 Twitter 搜索 API 的更多信息。