LoginSignup
0
2

More than 1 year has passed since last update.

twitterで特定アカウントのツイート一覧を取得する方法

Posted at

はじめに

ツイートを取得する方法を自分メモ用に残しておきます。

準備

ライブラリ

pip install tweepy

API取得

Twitter API を利用するには
(私はかなり前に取得したAPIを利用しましたが、以下のような記事を参考にすれば取得出来そうです。)

ツイート取得コード

  1. API情報とファイル名を修正してからファイル実行して下さい。
  2. コンソールで取得したいアカウントIDが聞かれるので入力して下さい。
twitter.py

import tweepy
from datetime import timedelta
import csv
import time

#API情報を記載
consumer_key = 'xxxx'
consumer_secret = 'xxxx'
access_token = 'xxxx'
access_token_secret = 'xxxx'

#保存するファイル名を記載
file_name='xxx.csv'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth)

info_list = []


def main():

    Account = input('Account:@')  # ツイートを抽出するアカウントIDを入力するためのInput関数

    num = 0  # 取得するツイートを計算する

    pages = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]  # ※2
    #pages = [1]
    for page in pages:

        tweets = api.user_timeline(Account, count=200, page=page)  # ※3

        for tweet in tweets:
            info_dic = {'time': '', 'content': ''}
            tweet.created_at += timedelta(hours=9)

            info_dic['time'] = tweet.created_at
            info_dic['content'] = tweet.text
            info_list.append(info_dic)
            num += 1
        time.sleep(2)

    with open(file_name, "w", encoding="utf_8_sig") as f:
        fieldnames = ['time', 'content']
        writer = csv.DictWriter(f, fieldnames=fieldnames, lineterminator="\n")
        writer.writeheader()
        for s in info_list:
            writer.writerow({'time': s['time'], 'content': s['content']})


if __name__ == '__main__':

    main()

0
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
0
2