Twitter API - 获取特定id的推文

38

我有一份推文ID列表,想要下载它们的文本内容。是否有任何简单的解决方案可以通过Python脚本完成,最好是通过Python脚本完成?我已经查看了其他库,如Tweepy,但似乎并不那么简单,而手动下载则不现实,因为我的列表非常长。


你所说的“简单”是什么意思?抱歉,没有这样的工具可以接收语音输入并下载推文,您需要编写代码。顺便说一句,tweepy是目前最易于使用和文档最完备的Twitter API库之一。 - ZdaR
4个回答

65
你可以使用 statuses/show/:id API 路径 来访问指定的推文。大多数 Python Twitter 库都遵循相同的模式,或提供方法的“友好”名称。
例如,Twython 提供了几个 show_* 方法,包括 Twython.show_status(),可以让你加载特定的推文:
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给出的推文对象定义

tweepy使用tweepy.get_status()

auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
api = tweepy.API(auth)

tweet = api.get_status(id_of_tweet)
print(tweet.text)

在这里,它返回了一个稍微丰富一些的对象,但其属性再次反映了已发布的API。


2
谢谢,非常有帮助!这正是我正在寻找的! - Crista23

10

在此分享我的工作,之前的答案大大加速了我的工作进程(感谢)。这个Python 2.7脚本从文件中获取推特ID的文本。请根据您的输入数据格式调整get_tweet_id();原始配置适用于https://github.com/mdredze/twitter_sandy上的数据。

2018年4月更新:回应@someone的错误报告(感谢)。这个脚本不再丢弃每100个推特ID(那是我的错误)。请注意,如果推特由于任何原因不可用,则批量获取将默默地跳过它。现在,如果响应大小与请求大小不同,脚本会发出警告。

'''
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:])

我已经尝试了你的代码,函数“statuses_lookup”没有返回任何值,甚至没有出现任何异常。你能告诉我可能出了什么问题吗? - charvi
2
它对我仍有效,在今晚测试过。你是否在apps.twitter.com生成了consumer key、consumer secret、oath token和oath token secret字符串,并将它们放入脚本中?你是否安装了tweepy?你是否使用了有效的推文ID(例如260244087901413376)?你把代码发布在哪里了? - chrisinmtown
@chrisinmtown 感谢您的回答。我也有一个包含数千条推文ID的CSV文件,我想使用Twitter API获取推文内容。我看了您的回答,但我有几个问题:1)您定义了几个函数(例如get_tweets_single和get_tweets_bulk)。它们是获取推文的不同解决方案吗?2)关于“get_tweets_single”,您提到它需要大量的HTTP请求,不建议使用。由于我每月只有50个请求的权限,您有什么建议吗?谢谢! :) - mOna

6

好的,它确实能工作,但是文本被截断为140个字符。我没有看到设置扩展模式的选项,你知道如何获取完整的推文文本吗?谢谢 - DataNoob

6

很遗憾,我没有足够的声望来添加实际评论,所以这是唯一的方法:

我在chrisinmtown的回答中发现了一个bug和奇怪的事情:

由于该bug,每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()

使用“Using”更好,因为它可以在速率限制之后继续工作。

api = tweepy.API(auth_handler=auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True)

感谢您报告这个bug - 似乎旧代码每隔100个ID就会丢弃一个,真糟糕。哦,下次请在我的名字前加上@,这样我就能收到通知了! - chrisinmtown

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接