11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Twitterからキーワード検索して画像を取得する

Last updated at Posted at 2016-07-16

タイトルの通り、Twitterの検索APIを利用して、特定のキーワードの画像をダウンロードするためのスクリプトになります。

https://github.com/Code-Hex/twippai
参考にしたのはここ。

実行環境
OS:OX X EI Capitan(10.11.5)
Python:2.7.10

標準ライブラリの他に、こららのインストールする必要があります。
requests
requests_oauthlib

#!/usr/bin/env/python
# coding: utf-8

import os
import json
import time
import requests
from hashlib import md5
from requests_oauthlib import OAuth1

def md5hex(str):
	a = md5()
	a.update(str)
	return a.hexdigest()
	
folder = './data'

#パスが存在していればTrueを返す
path = os.path.exists(folder)

if not path:
	os.mkdir(folder)

consumer_key = ''#your key
consumer_secret = ''#your key
access_token = ''#your key
access_token_secret = ''#your key

#Twitter APIについて以下参照
#https://syncer.jp/twitter-api-matome/get/search/tweets
url = 'https://api.twitter.com/1.1/search/tweets.json'
oauth = OAuth1(consumer_key,consumer_secret,
				access_token,access_token_secret)
				#署名メソッドの指定。なくても動いた
				#signaturemethod = 'HMAC-SHA1')
				
idnum = ''
count = 1
while count <= 10:
	#Twitterの検索演算子も使える
		query_form = {'q' : u'メタモン filter:images min_retweets:1',
										'lang' : 'ja',
										'count' : 100,
										'result_type' : 'recent',
										'max_id' : idnum}
		uri = requests.get(url, auth = oauth, params = query_form)
		json_loads = json.loads(uri.content)
		
		
		for data in json_loads['statuses']:
			if 'media' not in data['entities']:
				continue
			else:
				urls = data['entities']['media']
				media_urls = urls[0]['media_url']#画像のURLを取得
				downloads = requests.get(media_urls).content #画像のDL
				print media_urls + " " + str([count])
			#%sは文字列として置換
			
			#URLを16進数形式の文字列に返して、ファイル名としている?
			filename = '%s.jpg' % md5hex(urls[0]['media_url'])
			filepath = '%s/%s' % (folder, filename)
			
			images = open(filepath, 'wb')
			images.write(downloads)
			images.close()
			count += 1
		idum = data['id']
		time.sleep(1)
11
13
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
11
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?