LoginSignup
1
2

More than 5 years have passed since last update.

Python3/Twitter Application-only authenticationでツイート取得

Posted at

はじめに

ラッパーはtweepyを使っています。python-twitterではApplication-only authenticationがv3.3で追加されたようですが、試したところ自分の環境ではうまく動きませんでした。

動作確認環境

  • Tweepy 3.5.0
  • Python 3.5
  • Amazon Linux AMI release 2017.03

サンプルコード

#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-

import tweepy

# App-Onlyなのでcustomer key と secretは不要
consumer_key = '<consumer key>'
consumer_secret = '<consumer secret>'
auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)

keyword = 'ウンベラータ'

for tweet in api.search(q=keyword, count=100):
    print(tweet.text)

検索結果で次ページ以降も取得する場合

Tweepyのカーソルを利用すると過去分の遡りがラク。
上記コードのfor部分を以下のように変更。

for tweet in tweepy.Cursor(api.search, q=keyword, count=100).items():
    print(tweet.text)

出力結果をJSON形式でファイルに吐き出す例

JSON serialise用の _json variableを利用
参考:https://stackoverflow.com/questions/27900451/convert-tweepy-status-object-into-json

#!/usr/bin/env python3.5
# -*- coding: utf-8 -*-

import tweepy

consumer_key = '<consumer key>'
consumer_secret = '<consumer secret>'
auth = tweepy.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)

keyword = 'ウンベラータ'

tweet_list = []
for tweet in tweepy.Cursor(api.search, q=keyword, count=100).items():
    tweet_list.append(tweet._json)

import json
f = open("output.tweepy.json", "w")
json.dump(tweet_list, f, ensure_ascii=False)
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2