透過 Twitter API 蒐集資料

使用 Python 分析社群媒體資料

Alex Hanna

Computational Social Scientist

Twitter API

  • API:Application Programming Interface(應用程式介面)
    • 存取資料的方法
  • Twitter APIs
    • Search API
    • Ads API
    • Streaming API
使用 Python 分析社群媒體資料

Streaming API

  • Streaming API
    • 即時推文
  • Filter 端點
    • 關鍵字
    • 使用者 ID
    • 位置
  • Sample 端點
    • 隨機樣本
使用 Python 分析社群媒體資料

使用 tweepy 蒐集資料

  • tweepy
    • 存取 Streaming API 的 Python 套件
使用 Python 分析社群媒體資料

SListener

from tweepy import Stream
import time

class SListener(Stream):
    def __init__(self, api = None):
        self.output  = open('tweets_%s.json' %
            time.strftime('%Y%m%d-%H%M%S'), 'w')
        self.api = api or API()
    ...
使用 Python 分析社群媒體資料

tweepy 認證

from tweepy import OAuthHandler
from tweepy import API 

auth = OAuthHandler(consumer_key, consumer_secret)

auth.set_access_token(access_token, access_token_secret)
api = API(auth)
使用 Python 分析社群媒體資料

用 tweepy 蒐集資料

from tweepy import Stream

listen = SListener(api)

stream = Stream(auth, listen)
stream.sample()
使用 Python 分析社群媒體資料

一起來練習吧!

使用 Python 分析社群媒體資料

Preparing Video For Download...