2015-02-07 3 views
11

나는 자신의 텍스트 콘텐츠를 다운로드하고 싶은 트위트 ID 목록이 있습니다. 가능한 한 파이썬 스크립트를 통해이 작업을 수행하는 쉬운 솔루션이 있습니까? 나는 Tweepy와 같은 다른 도서관을 보았고 일들이 그렇게 단순하게 작동하지 않는 것처럼 보였고 수동으로 다운로드하는 것은 내 목록이 매우 길기 때문에 의문의 여지가 없습니다.Twitter API - 특정 ID로 트윗을 가져 오기

+0

단순함이란 무엇을 의미합니까? 죄송 합니다만 음성 입력을 받아서 트윗을 다운로드 할 수있는 도구가 없습니다. 코드 작성이 필요합니다. BTW tweepy는 가장 쉽고 잘 문서화 된 트위터 API 라이브러리 중 하나입니다. – ZdaR

답변

16

statuses/show/:id API route으로 특정 트윗을 ID로 액세스 할 수 있습니다. 대부분의 Python Twitter 라이브러리는 정확한 패턴을 따르거나 메서드에 '친숙한'이름을 제공합니다.

예를 들어, Twython은 특정 트윗을로드 할 수 있습니다 Twython.show_status() 포함 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에 의해 주어진 Tweet object definition을 따른다. 그것은 약간 풍부한 개체를 반환

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를 반영 :

tweepy librarytweepy.get_status() 사용합니다.

+0

감사합니다. 매우 유용합니다! 그게 바로 제가 찾고 있던 것이 었습니다! – Crista23

3

(감사합니다). 이 Python 2.7 스크립트는 파일에 저장된 트윗 ID의 텍스트를 가져옵니다. 입력 데이터 형식에 맞게 get_tweet_id()를 조정하십시오.

내가 버그와 chrisinmtown 대답 이상한 일을 발견 https://github.com/mdredze/twitter_sandy

''' 
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' 

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('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('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) 
    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('Fetching tweet for ID %s', tweet_id) 
      # API limits batch size to 100 
      if len(tweet_ids) < 100: 
       tweet_ids.append(tweet_id) 
      else: 
       get_tweet_list(twapi, tweet_ids) 
       tweet_ids = list() 
    # process rump of file 
    if len(tweet_ids) > 0: 
     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("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:]) 
+0

코드 "statuses_lookup"이 어떤 값도 반환하지 않고 예외가 발생하지 않았습니다. 무엇이 잘못 될 수 있는지에 대해 제게 제안 해주세요. – charvi

+0

나는 내가 시도한 코드를 게시했다.
charvi

+1

그것은 나에게 여전히 효과가 있으며, 오늘 밤 테스트됩니다. apps.twitter.com에서 소비자 키, 소비자 비밀, 맹세 토큰 및 맹 토큰 비밀 문자열을 생성하여 스크립트에 입력 했습니까? tweepy 설치 했습니까? 유효한 짹짹 ID (예 : 260244087901413376)를 사용하셨습니까? 코드를 어디에 게시 했습니까? – chrisinmtown

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() 

속도 제한을 초과하여도 작동하므로 사용하는 것이 좋습니다.

api = tweepy.API(auth_handler=auth, wait_on_rate_limit=True, wait_on_rate_limit_notify=True) 
관련 문제