Python Twitter API-获取具有特定id的推文

Python Twitter API-获取具有特定id的推文,python,twitter,Python,Twitter,我有一个tweet ID列表,我想下载它们的文本内容。有什么简单的解决方案可以做到这一点,最好是通过Python脚本?我看了一下其他的库,比如Tweepy,事情似乎不那么简单,手动下载它们是不可能的,因为我的列表很长。你可以通过id访问特定的推文。大多数Python Twitter库遵循完全相同的模式,或者为方法提供“友好”的名称 例如,提供了几种show.*方法,包括用于加载特定推文的方法: CONSUMER_KEY = "<consumer key>" CONSUMER_SECR

我有一个tweet ID列表,我想下载它们的文本内容。有什么简单的解决方案可以做到这一点,最好是通过Python脚本?我看了一下其他的库,比如Tweepy,事情似乎不那么简单,手动下载它们是不可能的,因为我的列表很长。

你可以通过id访问特定的推文。大多数Python Twitter库遵循完全相同的模式,或者为方法提供“友好”的名称

例如,提供了几种
show.*
方法,包括用于加载特定推文的方法:

CONSUMER_KEY = "<consumer key>"
CONSUMER_SECRET = "<consumer secret>"
OAUTH_TOKEN = "<application key>"
OAUTH_TOKEN_SECRET = "<application secret"
twitter = Twython(
    CONSUMER_KEY, CONSUMER_SECRET,
    OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

tweet = twitter.show_status(id=id_of_tweet)
print(tweet['text'])

它返回一个稍微丰富一些的对象,但上面的属性再次反映了发布的API。

您可以通过状态/查找端点批量访问推文(一次最多100条):

共享我的工作,这些工作被前面的答案大大加快了(谢谢)。这个Python 2.7脚本获取存储在文件中的tweet ID的文本。为您的输入数据格式调整get_tweet_id(); 原始数据配置为

2018年4月更新:对@someone bug报告的响应较晚(谢谢)。这个脚本不再丢弃每100个tweet ID(这是我的bug)。请注意,如果tweet因任何原因不可用,则批量获取会自动跳过它。现在,如果响应大小与请求大小不同,脚本将发出警告

'''
Gets text content for tweet IDs
'''

# standard
from __future__ import print_function
import getopt
import logging
import os
import sys
# import traceback
# third-party: `pip install tweepy`
import tweepy

# global logger level is configured in main()
Logger = None

# Generate your own at https://apps.twitter.com/app
CONSUMER_KEY = 'Consumer Key (API key)'
CONSUMER_SECRET = 'Consumer Secret (API Secret)'
OAUTH_TOKEN = 'Access Token'
OAUTH_TOKEN_SECRET = 'Access Token Secret'

# batch size depends on Twitter limit, 100 at this time
batch_size=100

def get_tweet_id(line):
    '''
    Extracts and returns tweet ID from a line in the input.
    '''
    (tagid,_timestamp,_sandyflag) = line.split('\t')
    (_tag, _search, tweet_id) = tagid.split(':')
    return tweet_id

def get_tweets_single(twapi, idfilepath):
    '''
    Fetches content for tweet IDs in a file one at a time,
    which means a ton of HTTPS requests, so NOT recommended.

    `twapi`: Initialized, authorized API object from Tweepy
    `idfilepath`: Path to file containing IDs
    '''
    # process IDs from the file
    with open(idfilepath, 'rb') as idfile:
        for line in idfile:
            tweet_id = get_tweet_id(line)
            Logger.debug('get_tweets_single: fetching tweet for ID %s', tweet_id)
            try:
                tweet = twapi.get_status(tweet_id)
                print('%s,%s' % (tweet_id, tweet.text.encode('UTF-8')))
            except tweepy.TweepError as te:
                Logger.warn('get_tweets_single: failed to get tweet ID %s: %s', tweet_id, te.message)
                # traceback.print_exc(file=sys.stderr)
        # for
    # with

def get_tweet_list(twapi, idlist):
    '''
    Invokes bulk lookup method.
    Raises an exception if rate limit is exceeded.
    '''
    # fetch as little metadata as possible
    tweets = twapi.statuses_lookup(id_=idlist, include_entities=False, trim_user=True)
    if len(idlist) != len(tweets):
        Logger.warn('get_tweet_list: unexpected response size %d, expected %d', len(tweets), len(idlist))
    for tweet in tweets:
        print('%s,%s' % (tweet.id, tweet.text.encode('UTF-8')))

def get_tweets_bulk(twapi, idfilepath):
    '''
    Fetches content for tweet IDs in a file using bulk request method,
    which vastly reduces number of HTTPS requests compared to above;
    however, it does not warn about IDs that yield no tweet.

    `twapi`: Initialized, authorized API object from Tweepy
    `idfilepath`: Path to file containing IDs
    '''    
    # process IDs from the file
    tweet_ids = list()
    with open(idfilepath, 'rb') as idfile:
        for line in idfile:
            tweet_id = get_tweet_id(line)
            Logger.debug('Enqueing tweet ID %s', tweet_id)
            tweet_ids.append(tweet_id)
            # API limits batch size
            if len(tweet_ids) == batch_size:
                Logger.debug('get_tweets_bulk: fetching batch of size %d', batch_size)
                get_tweet_list(twapi, tweet_ids)
                tweet_ids = list()
    # process remainder
    if len(tweet_ids) > 0:
        Logger.debug('get_tweets_bulk: fetching last batch of size %d', len(tweet_ids))
        get_tweet_list(twapi, tweet_ids)

def usage():
    print('Usage: get_tweets_by_id.py [options] file')
    print('    -s (single) makes one HTTPS request per tweet ID')
    print('    -v (verbose) enables detailed logging')
    sys.exit()

def main(args):
    logging.basicConfig(level=logging.WARN)
    global Logger
    Logger = logging.getLogger('get_tweets_by_id')
    bulk = True
    try:
        opts, args = getopt.getopt(args, 'sv')
    except getopt.GetoptError:
        usage()
    for opt, _optarg in opts:
        if opt in ('-s'):
            bulk = False
        elif opt in ('-v'):
            Logger.setLevel(logging.DEBUG)
            Logger.debug("main: verbose mode on")
        else:
            usage()
    if len(args) != 1:
        usage()
    idfile = args[0]
    if not os.path.isfile(idfile):
        print('Not found or not a file: %s' % idfile, file=sys.stderr)
        usage()

    # connect to twitter
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    api = tweepy.API(auth)

    # hydrate tweet IDs
    if bulk:
        get_tweets_bulk(api, idfile)
    else:
        get_tweets_single(api, idfile)

if __name__ == '__main__':
    main(sys.argv[1:])

我没有足够的声誉来添加实际的评论,很遗憾,这是一条路要走:

我在克里辛镇发现了一只虫子和一个奇怪的东西回答:

由于该错误,每100条推文都将被跳过。以下是一个简单的解决方案:

        if len(tweet_ids) < 100:
            tweet_ids.append(tweet_id)
        else:
            tweet_ids.append(tweet_id)
            get_tweet_list(twapi, tweet_ids)
            tweet_ids = list()

你说的简单是什么意思?很抱歉,没有这样的工具可以为您输入语音和下载推文,您需要编码,顺便说一句,tweepy是最简单、文档最完整的推文API库之一。谢谢,非常有用!那正是我要找的!我试过你的代码,函数“statuses\u lookup”没有返回任何值,我甚至没有得到任何异常。你能告诉我哪里有问题吗?它对我仍然有效,今晚测试。您是否在apps.twitter.com上生成了消费者密钥、消费者机密、宣誓令牌和宣誓令牌机密字符串,并将其放入脚本中?你安装了tweepy吗?您是否使用了有效的推特id(例如260244087901413376)?你把密码贴在哪里了?@chrisinmtown谢谢你的回答。我还有一个CSV文件,包括数千个推特ID,我想使用twitter API获取推特内容。我读了你的答案,但我有几个问题:1)你定义了几个函数(例如,get_tweets_single和get_tweets_bulk)。他们有不同的解决方案来获取推文吗?2) 关于
get\u tweets\u single
,您提到它需要大量HTTP请求,不推荐使用。由于我每月只能处理50个请求,您有什么建议?谢谢!:)感谢某人的错误报告-似乎旧代码每100个ID就会丢弃一次。哦,下次请在我的名字前面使用@,这样我会收到通知!嗯,它确实有效,但文本被截断为140个字符。我看不到设置扩展模式的选项,你知道如何获取完整的推文吗?谢谢
        if len(tweet_ids) < 100:
            tweet_ids.append(tweet_id)
        else:
            tweet_ids.append(tweet_id)
            get_tweet_list(twapi, tweet_ids)
            tweet_ids = list()
api = tweepy.API(auth_handler=auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)