通过 Twitter API 收集数据

在 Python 中分析社交媒体数据

Alex Hanna

Computational Social Scientist

Twitter API

  • API:应用程序编程接口
    • 访问数据的方法
  • Twitter API
    • 搜索 API
    • 广告 API
    • 流式 API
在 Python 中分析社交媒体数据

流式 API

  • 流式 API
    • 实时推文
  • 过滤端点
    • 关键词
    • 用户 ID
    • 位置
  • 抽样端点
    • 随机样本
在 Python 中分析社交媒体数据

使用 tweepy 收集数据

  • tweepy
    • 访问流式 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 中分析社交媒体数据

¡Vamos a practicar!

在 Python 中分析社交媒体数据

Preparing Video For Download...