Last active
July 21, 2018 14:15
-
-
Save n-taku/2447857e89af79c0e5f57bb063666340 to your computer and use it in GitHub Desktop.
Pythonを使ってTwitterで検索をかける
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#coding: UTF-8 | |
from requests_oauthlib import OAuth1Session | |
import json | |
import os | |
import sys, time, calendar | |
#twitterのapiを使用する際の認証 | |
CONSUMER_KEY = "〜〜〜" | |
CONSUMER_SECRET = "〜〜〜" | |
ACCESS_TOKEN = "〜〜〜" | |
ACCESS_TOKEN_SECRET = "〜〜〜" | |
#検索履歴保存テキスト | |
search_history_path='search_history.txt' | |
#検索ワード | |
searchText=u"サッカー" | |
#過去の検索情報を取得 | |
json_dict={} | |
if os.path.isfile(search_history_path): | |
f = open(search_history_path, 'r') | |
json_dict = json.load(f) | |
#過去のどのIDまで検索したか取得 | |
searchId=json_dict.get(searchText, 0) | |
#twitter認証 | |
twitter = OAuth1Session(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_TOKEN_SECRET) | |
#検索 | |
tweets="" | |
params = { | |
"q": searchText, | |
"lang": "ja", | |
"result_type": "recent", | |
"count": "1", | |
"tweet_mode":"extended", | |
"since_id": searchId | |
} | |
req = twitter.get("https://api.twitter.com/1.1/search/tweets.json?", params = params) | |
tweets = json.loads(req.text) | |
tid="" | |
result="" | |
for tweet in tweets["statuses"]: | |
#検索したidを取得 | |
tid = tweet["id_str"] | |
#日本時間を計算 | |
time_utc = time.strptime(tweet["created_at"], '%a %b %d %H:%M:%S +0000 %Y') | |
unix_time = calendar.timegm(time_utc) | |
time_local = time.localtime(unix_time) | |
japan_time = time.strftime("%Y-%m-%d %H:%M:%S", time_local) | |
result=result + japan_time + "\n" | |
#名前とidの取得 | |
result=result + tweet["user"]["name"] + ":" +tweet["user"]["screen_name"] + "\n" | |
#テキストの取得 | |
result=result + tweet["full_text"] + "\n" | |
#画像データのURLの取得 | |
if tweet.has_key("retweeted_status"): | |
retweeted_status = tweet['retweeted_status'] | |
if retweeted_status.has_key("extended_entities"): | |
media_list = retweeted_status['extended_entities']['media'] | |
for media in media_list: | |
result=result + media["media_url"] + "\n" | |
if tweet.has_key("extended_entities"): | |
media_list = tweet['extended_entities']['media'] | |
for media in media_list: | |
result=result + media["media_url"] + "\n" | |
#検索結果を表示 | |
print result | |
#検索したidを保存 | |
if tid != "": | |
json_dict[searchText]=tid | |
json_str=json.dumps(json_dict, ensure_ascii=False, encoding='utf8') | |
f2 = open(search_history_path, 'w') | |
f2.write(json_str.encode('utf-8')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment