【问题标题】:Fetching tweets with hashtag from Twitter using Python [closed]使用 Python 从 Twitter 获取带有标签的推文 [关闭]
【发布时间】:2012-12-18 20:39:55
【问题描述】:

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

谢谢

【问题讨论】:

标签: python twitter twython


【解决方案1】:

编辑 我使用 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'

原答案

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 条推文,最多可能会回到一两周左右。你可以阅读更多关于 Twitter 搜索 API here

【讨论】:

  • 嘿,再次感谢,但我在执行此操作时遇到错误以下是我遇到的错误。是不是需要认证
  • TwythonError Traceback(最近一次通话最后)/home/vishal/ in () ----> 1 search_results = twitter.search(q= "#india", rpp="50") /usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc 在搜索中(自我,** kwargs) 365 """ 366 --> 367 return self.get('api.twitter.com/1.1/search/tweets.json', params=kwargs) 368 369 def searchGen(self, search_query, **kwargs):
  • usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc in get(self, endpoint, params, version) 236 237 def get(self, endpoint, params=None, version='1.1'): --> 238 return self.request(endpoint, params=params, version=version) 239 240 def post(self, endpoint, params=无,文件=无,版本='1.1'):
  • /usr/local/lib/python2.7/dist-packages/twython-2.5.5-py2.7.egg/twython/twython.pyc in request(self, endpoint, method, params , 文件, 版本) 231 url = '%s/%s.json' % (self.api_url % 版本, 端点) 232 --> 233 内容 = self._request(url, method=method, params=params, files=文件,api_call=url) 234 235 返回内容
  • 嘿,谢谢本杰明.......干杯。我欠你啤酒给这个朋友
猜你喜欢
  • 2013-12-16
  • 2015-03-02
  • 2014-04-15
  • 2018-12-23
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-02
相关资源
最近更新 更多