twitterからデータを拾う
以下,Python3を使って,twitterからデータを取得する方法を説明します.
準備
まず下記ページを参考に,自分のアプリケーション用のトークンやキーを手に入れます.
https://syncer.jp/Web/API/Twitter/REST_API/
config.pyというファイルに設定します.これは間違ってもgitとかに上げたりして公開してはダメですよ.
CONSUMER_KEY = "XXXXXXXXXXXX"
CONSUMER_SECRET = "YYYYYYYYYYYYYYY"
ACCESS_TOKEN = "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZZ"
ACCESS_TOKEN_SECRET = "____________________________"
twitterにはrequests-oauthlibでアクセスします.
requests-oauthlibを使ったことがなければ,インストールしておきましょう.
sudo pip3 install requests requests-oauthlib
twitterにアクセス
次にconfig.pyとその他必要なライブラリをインポートするソースコードを書きます.
import json, sys, config, re
from requests_oauthlib import OAuth1Session
CK = config.CONSUMER_KEY
CS = config.CONSUMER_SECRET
AT = config.ACCESS_TOKEN
ATS = config.ACCESS_TOKEN_SECRET
tw = OAuth1Session(CK, CS, AT, ATS)
baseurl = "https://api.twitter.com/1.1"
指定したユーザのツイート群を取得するコードです.baseurlに,APIのURLを付加します.
tweet_url = baseurl + "/search/tweets.json"
def getTweets(name):
res = tw.get(tweet_url, params = { 'q': "from:" + name })
tweets = json.loads(res.text)
return tweets
指定したユーザのお気に入りを取得するコードです.同様に,baseurlに,APIのURLを付加します.
favorites_url = baseurl + "/favorites/list.json"
def getFavorites(name):
res = tw.get(favorites_url, params = { 'screen_name': name })
tweets = json.loads(res.text)
return tweets
ツイートの中にURLがある時は,短縮されているので復号する必要があります.
URLにアクセスすると,301が返ってくるので,locationヘッダの値を返却します.
def expandURL(url):
conn = http.client.HTTPSConnection("t.co")
conn.rquest("GET", url)
res = conn.getresponse()
if res.status == 301:
hdr = res.getheader("location")
return hdr
else:
return None
さてこのツイート群ですが,一個一個の取得結果が妙に長いです.
ツイート主のアカウント情報まるまるや,場合によってはツイート時の緯度経度まで含みます.
多分 text と created_at くらいで10中8,9は足りるのではないでしょうか.
{'created_at': 'Mon Sep 24 11:08:48 +0000 2018',
'id': 1044181851554734080, 'id_str': '1044181851554734080',
'text': '何が起こっているのか簡単に書くと,アティヤという超有名な数学者(でももう89歳のおじいちゃん)が微細構造定数(要するに電磁相互作用の無次元の強さ)の値を計算で出して,そのついでにリーマン予想を証明しちゃったというので騒ぎになっている(老人の妄想?)',
'truncated': False,
'entities': {'hashtags': [], 'symbols': [], 'user_mentions': [], 'urls': []},
'source': '<a href="http://twmode.sf.net/" rel="nofollow">twmode</a>',
'in_reply_to_status_id': None, 'in_reply_to_status_id_str': None,
'in_reply_to_user_id': None, 'in_reply_to_user_id_str': None,
'in_reply_to_screen_name': None, 'user': {'id': 28894757, 'id_str': '28894757',
'name': 'Haruhiko Okumura', 'screen_name': 'h_okumura', 'location': 'Japan',
'description': 'https://t.co/714NuCih81 転載はご自由に(CC BY)', 'url': None,
'entities': {'description': {'urls': [{'url': 'https://t.co/714NuCih81',
'expanded_url': 'http://oku.edu.mie-u.ac.jp/~okumura/',
'display_url': 'oku.edu.mie-u.ac.jp/~okumura/', 'indices': [0, 23]}]}},
'protected': False, 'followers_count': 22653, 'friends_count': 493,
'listed_count': 1687, 'created_at': 'Sat Apr 04 23:33:18 +0000 2009',
'favourites_count': 3075, 'utc_offset': None, 'time_zone': None,
'geo_enabled': True, 'verified': False, 'statuses_count': 70275, 'lang': 'ja',
'contributors_enabled': False, 'is_translator': False,
'is_translation_enabled': False, 'profile_background_color': 'C0DEED',
'profile_background_image_url': http://abs.twimg.com/images/themes/theme1/bg.png',
'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png',
'profile_background_tile': False,
'profile_image_url': 'http://pbs.twimg.com/profile_images/3621816458/b159d4051d6a227bcaf7f265e1d92da4_normal.jpeg',
'profile_image_url_https':
'https://pbs.twimg.com/profile_images/3621816458/b159d4051d6a227bcaf7f265e1d92da4_normal.jpeg', 'profile_link_color': '1DA1F2',
'profile_sidebar_border_color': 'C0DEED', 'profile_sidebar_fill_color': 'DDEEF6',
'profile_text_color': '333333',
'profile_use_background_image': True, 'has_extended_profile': False,
'default_profile': True, 'default_profile_image': False, 'following': True,
'follow_request_sent': False, 'notifications': False, 'translator_type': 'none'},
'geo': None, 'coordinates': None, 'place': None, 'contributors': None,
'is_quote_status': False, 'retweet_count': 1243, 'favorite_count': 1717,
'favorited': True, 'retweeted': False, 'lang': 'ja'}
あとはやりたいことをAPIを見て探してください.
https://developer.twitter.com/en.html
いくつか注意があります.
- 検索できるツイート件数には限りがあります.課金で増やせるはずです.
- ユーザー間の関係(フォローしているとかされているとか)は,少しずつしか探せません.課金しても増やせません.