나는 자신의 텍스트 콘텐츠를 다운로드하고 싶은 트위트 ID 목록이 있습니다. 가능한 한 파이썬 스크립트를 통해이 작업을 수행하는 쉬운 솔루션이 있습니까? 나는 Tweepy와 같은 다른 도서관을 보았고 일들이 그렇게 단순하게 작동하지 않는 것처럼 보였고 수동으로 다운로드하는 것은 내 목록이 매우 길기 때문에 의문의 여지가 없습니다.Twitter API - 특정 ID로 트윗을 가져 오기
답변
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
library는 tweepy.get_status()
사용합니다.
감사합니다. 매우 유용합니다! 그게 바로 제가 찾고 있던 것이 었습니다! – Crista23
당신은 상태/조회 엔드 포인트에 (한 번에 100까지) 대량으로 트윗에 액세스 할 수 있습니다 훨씬 이전 답변에 의해 가속 된 내 작품을 공유 https://dev.twitter.com/rest/reference/get/statuses/lookup
(감사합니다). 이 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:])
코드 "statuses_lookup"이 어떤 값도 반환하지 않고 예외가 발생하지 않았습니다. 무엇이 잘못 될 수 있는지에 대해 제게 제안 해주세요. – charvi
나는 내가 시도한 코드를 게시했다.
–
charvi
그것은 나에게 여전히 효과가 있으며, 오늘 밤 테스트됩니다. apps.twitter.com에서 소비자 키, 소비자 비밀, 맹세 토큰 및 맹 토큰 비밀 문자열을 생성하여 스크립트에 입력 했습니까? tweepy 설치 했습니까? 유효한 짹짹 ID (예 : 260244087901413376)를 사용하셨습니까? 코드를 어디에 게시 했습니까? – chrisinmtown
에서 데이터를 구성 원래 내가 실제 댓글을 추가 할 수있는 충분한 명성을하지 않아도 그렇게 슬프게이 길을 가야하는 것입니다 :
모든 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)
- 1. Twitter API 검색 - 특정 트윗을 제외하는 법?
- 2. ID로 많은 트윗을 당기기
- 3. Twitter API 사용자 만 가져 오기
- 4. 특정 트위터 사용자의 트윗을 가져 오시겠습니까?
- 5. Twitter API PHP 최신 트윗을 인증하지 않음
- 6. 유니버설 트윗을 Twitter API v1.1을 통해 검색하려면
- 7. 특정 추종자가 트윗을 보지 못하게 할 수 있습니까? (Twitter API)
- 8. Jenkins Python API : ID로 QueueItem 가져 오기
- 9. ID로 세션 가져 오기
- 10. Twitter API 화면 이름으로 최신 트윗을 가져 오는 중
- 11. ID로 세션 가져 오기
- 12. 사용자 미디어 (사진) 만 가져 오기 - Twitter API
- 13. Twitter API (Twitter4j). 미국의 트윗을 얻는 방법?
- 14. Twitter API - gps 포인트 근처에서 트윗을 얻으십시오.
- 15. Twitter API : 가까운 최신 트윗을 받으십시오.
- 16. 사용자 프로필 가져 오기 pic twitter api
- 17. Twitter - 특정 GeoLocation 반경 내에서 트윗을 쿼리하십시오.
- 18. twitter4j - ID로 트윗을
- 19. twitter api를 사용하여 특정 기간의 트윗을 표시하는 방법
- 20. Twitter API - 단일 사용자로부터 해시 태그 가져 오기
- 21. id로 요소 가져 오기
- 22. id로 개체 가져 오기
- 23. 해시 태그로 트윗을 file_get_contents로 가져 오기
- 24. JSON (Twitter API)의 다음 항목에서 정보 가져 오기
- 25. id로 facebook 코멘트 가져 오기
- 26. 동영상 ID로 동영상 가져 오기
- 27. Vimeo API v3 : 앨범 ID로 동영상 가져 오기
- 28. Twitter API : 일정 기간에서 사용자의 트윗을 얻는 방법?
- 29. Twitter API 사용
- 30. Twitter 상태/user_timeline에서 사진 가져 오기
단순함이란 무엇을 의미합니까? 죄송 합니다만 음성 입력을 받아서 트윗을 다운로드 할 수있는 도구가 없습니다. 코드 작성이 필요합니다. BTW tweepy는 가장 쉽고 잘 문서화 된 트위터 API 라이브러리 중 하나입니다. – ZdaR