Practicando con la API de Twitter

Instalacion de tweepy (para python2) en Anaconda3

Creamos un eviorent con py2 e instalamos sobre el

conda create -n py2 python=2 anaconda
source activate py2
/home/guadatech/anaconda3/envs/py2/bin/easy_install tweepy

Ejecutamos el notebook en el entorno creado

/home/guadatech/anaconda3/envs/py2/bin/ipython notebook

In [1]:
import tweepy
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('datosCuentaTwitter.ini')

APP_KEY = config.get('DatosTwitter','APP_KEY')
APP_SECRET = config.get('DatosTwitter','APP_SECRET')
OAUTH_TOKEN = config.get('DatosTwitter','OAUTH_TOKEN')
OAUTH_TOKEN_SECRET = config.get('DatosTwitter','OAUTH_TOKEN_SECRET')

auth = tweepy.OAuthHandler(APP_KEY, APP_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
api = tweepy.API(auth)

In [2]:
public_tweets = api.home_timeline(count=2)
for tweet in public_tweets:
    print(tweet.user.screen_name)
    print(tweet.created_at)
    print tweet.text
    print(' *'*40)


LaVanguardia
2015-12-15 13:05:42
Cada vez estamos más conectados: la teoría de los seis grados pasa a cuatro https://t.co/fKlanP3eQZ Por @santijustel
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
20m
2015-12-15 13:05:09
#BLOG  Le roba la cartera y después lo salva de morir arrollado por el metro https://t.co/lVBUM4etKK @elbecario https://t.co/YVLsXiMN0Q
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py:90: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
  InsecurePlatformWarning

In [ ]:
# Busqueda informacion
for tweet in api.search(q='GeekyTheory',count=4, result_type='recent'):
    print(tweet.created_at)
    print(tweet.user.screen_name)
    print(tweet.text)
    print(' *'*40)

In [36]:
# Obteniendo todos los tweets del timeline del usuario entre dos fechas determinadas
import datetime

startDate = datetime.datetime(2015, 12, 7, 0, 30, 0)  #2015-12-07 12:15:12
endDate =   datetime.datetime(2015, 12, 7, 1, 0, 0)

tweets = []
tempTweets = []
tmpTweets = api.home_timeline()
for tweet in tmpTweets:
    if tweet.created_at < endDate and tweet.created_at > startDate:
        tweets.append(tweet)

while (tmpTweets[-1].created_at > startDate):
    print("Last Tweet @", tmpTweets[-1].created_at, " - fetching some more")
    tmpTweets = api.home_timeline(max_id = tmpTweets[-1].id, count=20)
    for tweet in tmpTweets:
        if tweet.created_at < endDate and tweet.created_at > startDate:
            tweets.append(tweet)

print("Numero de Tweets: %d"% len(tweets))
for tweet in tweets:
    print(tweet.created_at)
    print(tweet.user.screen_name)
    print(tweet.text)
    print(' *'*40)


---------------------------------------------------------------------------
RateLimitError                            Traceback (most recent call last)
<ipython-input-36-c3d9e5a5d337> in <module>()
      7 tweets = []
      8 tempTweets = []
----> 9 tmpTweets = api.home_timeline()
     10 for tweet in tmpTweets:
     11     if tweet.created_at < endDate and tweet.created_at > startDate:

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/binder.pyc in _call(*args, **kwargs)
    241             return method
    242         else:
--> 243             return method.execute()
    244 
    245     # Set pagination mode

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/binder.pyc in execute(self)
    223 
    224                 if is_rate_limit_error_message(error_msg):
--> 225                     raise RateLimitError(error_msg, resp)
    226                 else:
    227                     raise TweepError(error_msg, resp)

RateLimitError: [{u'message': u'Rate limit exceeded', u'code': 88}]

In [64]:
# Otro metodo 
cont = 0
for tweet in tweepy.Cursor(api.search,q='ciudadanos,elmundoes', since="2015-12-06", until="2015-12-07").items(100):
    cont += 1
    print(cont)
    print(tweet.created_at)
    print(tweet.user.screen_name)
    print(tweet.text)
    print(' *'*40)


1
2015-12-06 22:49:16
Mariaescrivana
RT @prnoticias: Sigma Dos: El candidato de @el_pais y @elmundoes es @Albert_Rivera de @CiudadanosCs ¿Sabes por qué? 🔎🔎🔎 https://t.co/X7AxQf…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2
2015-12-06 22:35:43
cuantademagogia
RT @elmundoes: Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
3
2015-12-06 22:28:09
cb3rmud3z
RT @elmundoes: Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
4
2015-12-06 22:17:32
ERMNoticias
'Si las cosas no cambian hoy en Venezuela, no lo harán nunca': Los ciudadanos votan con l... https://t.co/fi8QOas3KE #ERMmedia @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
5
2015-12-06 22:17:30
LuisRosarioM
'Si las cosas no cambian hoy en Venezuela, no lo harán nunca': Los ciudadanos votan con l... https://t.co/5rsisu9HfG #ERMmedia @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6
2015-12-06 21:45:04
pirriqui2011
Hay que tener cara !!!
Susana Díaz alerta de que votar a Ciudadanos o a Podemos es apostar por el PP https://t.co/rEOJfZRNvW vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
7
2015-12-06 21:43:21
conde_suarez
RT @Kurgancin: De lo más interesante que he leído sobre Rivera. https://t.co/bQ5IOv2aBy vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
8
2015-12-06 21:15:57
4444isa
Ciudadanos: terapia de grupo para llegar a La Moncloa https://t.co/EJXXoAmX4y vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
9
2015-12-06 21:10:18
Yo_Ciudadanos
RT @elmundoes: #LaPortada del sábado 5 de diciembre https://t.co/MGEAMJjbPx
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
10
2015-12-06 21:05:13
ESTEVEZPACO
Susana Díaz alerta de que votar a Ciudadanos es apostar por el PP ¿ votar presupuestos para esto...? https://t.co/c9KAKSrFhq vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
11
2015-12-06 19:49:20
equoalcala
Con garantías reales?Ciudadanos financiará la campaña con un crédito del Banco Popular de 4 millones https://t.co/Sz1Kszdj7h vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
12
2015-12-06 19:33:22
vicentelozano
Políticos y ciudadanos deberíamos preguntarnos por qué.  https://t.co/n3sGrvXGUq
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
13
2015-12-06 19:33:20
solyramar
Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' https://t.co/CCzoHY6HmQ vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
14
2015-12-06 19:08:38
piyogaca
RT @RLSerrano: https://t.co/61dfigOx6b Ni @elpais_espana, ni @elmundoes, ni @laSextaTV, ni @A3Noticias te contarán la verdad sobre #Ciudada…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
15
2015-12-06 19:04:48
MJesusCalderon
Como está el patio !! Susana Díaz alerta de que votar a Ciudadanos o a Podemos es apostar por el PP https://t.co/VPdcY7ZiTE vía elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
16
2015-12-06 18:46:38
LuisMFuentes70
Qué arte tiene "Susana Díaz alerta de que votar a Ciudadanos o a Podemos es apostar por el PP" https://t.co/iJajFn6hhK vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
17
2015-12-06 18:01:49
AidaPFV
@crispapin @PSpresidente @elmundoes @el_pais El País puede ser que lo ponga,mientras no se hable mal de Ciudadanos,todo les parece bien.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
18
2015-12-06 17:48:09
carmencp76
RT @carloscuestaEM: El PP ganaría por 8 puntos al PSOE que casi empataría con Ciudadanos https://t.co/AGscznE4OP vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
19
2015-12-06 17:31:46
BobEspo19582015
RT @romulense: Marjaliza dice ante el juez que pagó viajes a dos cargos de Ciudadanos https://t.co/z4g0t8N11K vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
20
2015-12-06 17:11:33
cgfp58
RT @elmundoes: Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
21
2015-12-06 17:02:26
Carlos_Aranzana
RT @RLSerrano: https://t.co/61dfigOx6b Ni @elpais_espana, ni @elmundoes, ni @laSextaTV, ni @A3Noticias te contarán la verdad sobre #Ciudada…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
22
2015-12-06 16:59:26
MeliDeNervion
RT @MiguelSanz92: ¡¡OJO!! Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda. https://t.co/Tf76Yx2AJK vía @elmu…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
23
2015-12-06 16:34:00
villamarilis
RT @yosoynaranjito_: Ciudadanos: terapia de grupo para llegar a La Moncloa https://t.co/TPfzCkDj5b vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
24
2015-12-06 16:21:43
PedroCsAlba
RT @RLSerrano: https://t.co/61dfigOx6b Ni @elpais_espana, ni @elmundoes, ni @laSextaTV, ni @A3Noticias te contarán la verdad sobre #Ciudada…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
25
2015-12-06 16:15:47
RLSerrano
https://t.co/61dfigOx6b Ni @elpais_espana, ni @elmundoes, ni @laSextaTV, ni @A3Noticias te contarán la verdad sobre #Ciudadanos y Rivera.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
26
2015-12-06 16:12:58
yosoynaranjito_
Ciudadanos: terapia de grupo para llegar a La Moncloa https://t.co/TPfzCkDj5b vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
27
2015-12-06 15:58:37
CapitanFeria
@Perroviejo1982 @elmundoes Y el PP dice q votar Ciudadanos es votar Sanchez.
Lo q esta claro es q son Ciudadanos camaleonicos.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
28
2015-12-06 15:52:59
Perroviejo1982
Susana Díaz alerta de que votar a Ciudadanos o a Podemos es apostar por el PP https://t.co/UES0a5oB46 vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
29
2015-12-06 15:18:22
komadreja6
RT @MiguelSanz92: ¡¡OJO!! Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda. https://t.co/Tf76Yx2AJK vía @elmu…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
30
2015-12-06 15:00:16
JqManso
@GalvanX @elmundoes Esta noche están en juego ésa y todas las demás libertades políticas de 31 millones de ciudadanos de Venezuela.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
31
2015-12-06 14:52:25
JqManso
Ciudadanos:'focus group' para medir las sensaciones del votante. https://t.co/UVerGRIKLk vía @_raulpina_ @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
32
2015-12-06 14:37:09
cramosr13
RT @MiguelSanz92: ¡¡OJO!! Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda. https://t.co/Tf76Yx2AJK vía @elmu…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
33
2015-12-06 14:14:45
agataparda
@Papel_EM @elmundoes  Ciudadanos se desinfla: no logra concentrar ni a 60 personas en Valencia,la mayoría afiliados. https://t.co/MuHLGReWQu
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
34
2015-12-06 13:38:31
Niccomalc
RT @MiguelSanz92: ¡¡OJO!! Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda. https://t.co/Tf76Yx2AJK vía @elmu…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
35
2015-12-06 13:28:44
carnedecapital
RT @romulense: Marjaliza dice ante el juez que pagó viajes a dos cargos de Ciudadanos https://t.co/z4g0t8N11K vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
36
2015-12-06 12:50:52
elmundomalaga
Batalla por el centro a la derecha https://t.co/EIKqVoLVEV vía @elmundoes por @luismcarceller #segundaplana #elecciones20D #ciudadanos #pp
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
37
2015-12-06 12:48:34
MarieneMoreno
RT @CsMajadahonda: .@Albert_Rivera rechaza 'cuatro años más con Rajoy' https://t.co/1mXJQ2KXld vía @elmundoes #ciudadanos
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
38
2015-12-06 11:13:34
mariaabadmullor
CANDIDATURA ÚNICA YA!!!  Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' https://t.co/LsBHKjvq8d vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
39
2015-12-06 11:13:20
rociocalderonmz
RT @elmundoes: Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
40
2015-12-06 11:09:29
amalalberga
Ciudadanos propone a los universitarios ser 'comerciales' de la agricultura española https://t.co/p8xtt9uFr5 vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
41
2015-12-06 10:32:47
Fercampos45
Marjaliza dice ante el juez que pagó viajes a dos cargos de Ciudadanos https://t.co/PUnuXQkMhm vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
42
2015-12-06 10:17:20
conde_suarez
RT @marich: Ciudadanos: más poesía que prosa https://t.co/HZjiD1f0X9 vía @elmundoes por @conde_suarez
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
43
2015-12-06 09:50:58
_raulpina_
Ciudadanos: terapia de grupo para llegar a La Moncloa. Así son los focus group en la política  https://t.co/67L5ivqB5p vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
44
2015-12-06 09:47:04
trinidad1956
RT @elmundoes: Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
45
2015-12-06 09:38:41
antonovas
RT @romulense: Marjaliza dice ante el juez que pagó viajes a dos cargos de Ciudadanos https://t.co/z4g0t8N11K vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
46
2015-12-06 09:05:24
mohatam
RT @romulense: Marjaliza dice ante el juez que pagó viajes a dos cargos de Ciudadanos https://t.co/z4g0t8N11K vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
47
2015-12-06 09:01:32
romulense
Marjaliza dice ante el juez que pagó viajes a dos cargos de Ciudadanos https://t.co/z4g0t8N11K vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
48
2015-12-06 08:11:55
djvarell
RT @HoradeJugar: Ciudadanos financiará la campaña con un crédito del Banco Popular, el de los curas, de 4 millones https://t.co/c8XjsML9UT …
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
49
2015-12-06 08:11:21
jesuschatinova1
@elmundoes Yo creo que una gran parte debería ser para todos aquellos ciudadanos de esos países que residen en España.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
50
2015-12-06 04:39:55
SerranoJaen
Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' https://t.co/ugv8zaldWJ vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
51
2015-12-06 03:32:22
jmle01
Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' https://t.co/z149UEqzQb vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
52
2015-12-06 01:45:25
gadearevilla
RT @elmundoes: Pedro Sánchez ofrecerá a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
53
2015-12-06 01:31:24
mjpartera
Ciudadanos quiere regular los vientres de alquiler en España https://t.co/2a0HJenE3q vía elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
54
2015-12-06 01:05:37
PacoBono
@elmundoes @rterrasa Porque son falsas, porque los ciudadanos no eligen nada. Si fueran verdaderas se disputarían en los distritos.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
55
2015-12-06 00:42:37
CsVegasDelGenil
RT @CsMajadahonda: .@Albert_Rivera rechaza 'cuatro años más con Rajoy' https://t.co/1mXJQ2KXld vía @elmundoes #ciudadanos
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
56
2015-12-06 00:20:31
ANTONIO39R
RT @CsMajadahonda: .@Albert_Rivera rechaza 'cuatro años más con Rajoy' https://t.co/1mXJQ2KXld vía @elmundoes #ciudadanos
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
57
2015-12-06 00:19:45
CsMajadahonda
.@Albert_Rivera rechaza 'cuatro años más con Rajoy' https://t.co/1mXJQ2KXld vía @elmundoes #ciudadanos
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

In [54]:
# Otro metodo 
cont = 0
for tweet in tweepy.Cursor(api.user_timeline,id="elmundoes").items(10):
    cont += 1
    print(cont)
    print(tweet.created_at)
    print(tweet.user.screen_name)
    print(tweet.text)
    print(' *'*40)


1
2015-12-07 18:16:21
elmundoes
RT @ElMundo_Madrid: Si estás preparando tu regreso a Madrid, anota los puntos negros de las principales vías https://t.co/e6hNncEEuT https:…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
2
2015-12-07 18:11:52
elmundoes
RT @ElMundoEspana: Sánchez, Iglesias, Rivera y Santamaría debatirán de pie, sin atriles ni móviles
https://t.co/ysFGtjv9HS https://t.co/70p…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
3
2015-12-07 17:55:13
elmundoes
Condenado un maltratador que inyectaba cocaína en los pechos a su víctima https://t.co/h07X8znWYk https://t.co/mFBl1kcQEJ
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
4
2015-12-07 17:47:52
elmundoes
RT @ElMundoEconomia: El 'Black Friday' bate el récord histórico de solicitudes para comprar armas en EEUU https://t.co/r4h73mIo2b vía @elmu…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
5
2015-12-07 17:34:37
elmundoes
Una "primera ministra" y tres aspirantes #7DElDebateDecisivo https://t.co/VuqaGJWlVs https://t.co/wk07DtugPF
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
6
2015-12-07 17:15:27
elmundoes
RT @ElMundoEspana: El cartel que avergüenza al PP https://t.co/VYPIajE7dT https://t.co/80c6P1VQvy
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
7
2015-12-07 17:04:47
elmundoes
RT @fpasc: La imagen de Pedro Sánchez: guapo, pero ¿algo más? https://t.co/K32H9j1P8D vía @PoliticayModa
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
8
2015-12-07 16:52:30
elmundoes
Le quitan la custodia de su hijo por 'falta de recursos económicos y vivienda propia' https://t.co/COuJlNv8ES https://t.co/xMub1oS12G
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
9
2015-12-07 16:37:09
elmundoes
RT @ElMundoEspana: El 'crowdfunding' de Ciudadanos: por 500 euros puedes ser por un día dirigente de Rivera  https://t.co/Nj8tvOfltk https:…
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
10
2015-12-07 16:29:37
elmundoes
RT @Inaki_Gil: Los segundos serán los primeros ... dice Jiménez Losantos https://t.co/HmifhASDjm vía @elmundoes
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

In [19]:
import datetime

def buscaTweetsPorTerminosYFechas(usuario,terminos, desde, hasta):
    """ Funcion para devolver los tweets que contengan una lista de terminos
        de una fecha desde a una fecha hasta, los terminos y las fechas se han de dar en cadenas """
    busqueda = ','.join(terminos)
    tweets = []
    tweetsUnicos = set()
    for tweet in tweepy.Cursor(api.search,q=busqueda, since=desde, until=hasta).items(100):
        if usuario == tweet.user.screen_name and not tweet.text in tweetsUnicos:
            tweets.append((tweet.created_at,tweet.text))
            tweetsUnicos.add(tweet.text)
    return tweets

In [20]:
tweets = buscaTweetsPorTerminosYFechas('elmundoes',['ciudadanos'],"2015-12-07","2015-12-08" )
print(len(tweets))


---------------------------------------------------------------------------
TweepError                                Traceback (most recent call last)
<ipython-input-20-14328fa76286> in <module>()
----> 1 tweets = buscaTweetsPorTerminosYFechas('elmundoes',['ciudadanos'],"2015-12-07","2015-12-08" )
      2 print(len(tweets))

<ipython-input-19-6d1699c67ca0> in buscaTweetsPorTerminosYFechas(usuario, terminos, desde, hasta)
      8     tweets = []
      9     tweetsUnicos = set()
---> 10     for tweet in tweepy.Cursor(api.search,q=busqueda, since=desde, until=hasta).items(100):
     11         if usuario == tweet.user.screen_name and not tweet.text in tweetsUnicos:
     12             tweets.append((tweet.created_at,tweet.text))

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/cursor.pyc in next(self)
    195         if self.current_page is None or self.page_index == len(self.current_page) - 1:
    196             # Reached end of current page, get the next page...
--> 197             self.current_page = self.page_iterator.next()
    198             self.page_index = -1
    199         self.page_index += 1

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/cursor.pyc in next(self)
    106 
    107         if self.index >= len(self.results) - 1:
--> 108             data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs)
    109 
    110             if hasattr(self.method, '__self__'):

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/binder.pyc in _call(*args, **kwargs)
    241             return method
    242         else:
--> 243             return method.execute()
    244 
    245     # Set pagination mode

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/binder.pyc in execute(self)
    225                     raise RateLimitError(error_msg, resp)
    226                 else:
--> 227                     raise TweepError(error_msg, resp)
    228 
    229             # Parse the response payload

TweepError: {"errors":[{"message":"Rate limit exceeded","code":88}]}

In [15]:
print(tweets)


[(datetime.datetime(2015, 12, 7, 23, 47, 32), u'Andresss2308', u'@ElMundoEnVivo @elmundoes Soraya los atendi\xf3. Rivera muy bien si no existiera el revoltoso Iglesias votar\xeda ciudadanos. Mi voto PP'), (datetime.datetime(2015, 12, 7, 20, 40, 42), u'ERMNoticias', u"'Esto es el fin de la ruina y las mentiras en Venezuela': Los ciudadanos venezolanos reci... https://t.co/IsuH1Q19Ih #ERMmedia @elmundoes"), (datetime.datetime(2015, 12, 7, 20, 40, 39), u'LuisRosarioM', u"'Esto es el fin de la ruina y las mentiras en Venezuela': Los ciudadanos venezolanos reci... https://t.co/roAfDRo8Zu #ERMmedia @elmundoes"), (datetime.datetime(2015, 12, 7, 20, 26, 51), u'EFEmolina', u"RT @elmundoes: Pedro S\xe1nchez ofrecer\xe1 a Ciudadanos y Podemos un pacto 'anti PP' aunque pierda https://t.co/uJc4eyODau https://t.co/xIKSjaLA\u2026"), (datetime.datetime(2015, 12, 7, 20, 22, 49), u'lolaq20', u'Ciudadanos financiar\xe1 la campa\xf1a con un cr\xe9dito del Banco Popular de 4 millones https://t.co/b2qXparGCu v\xeda @elmundoes'), (datetime.datetime(2015, 12, 7, 18, 0, 58), u'Jbelli59', u'@elisamonachil @elmundoes y para colmo lo mas duro es lo de ciudadanos con el royo de la responsabilidad apoyando mas de lo mismo los listos'), (datetime.datetime(2015, 12, 7, 17, 59, 11), u'Albert__MV', u"Ciudadanos pone en marcha un 'crowdfunding': por 500\u20ac puedes ser por un d\xeda dirigente de Albert Rivera \nhttps://t.co/rL9FzYUEMd  @elmundoes"), (datetime.datetime(2015, 12, 7, 17, 58, 15), u'Jbelli59', u'@elisamonachil @elmundoes lo que es una pena para el resto de ciudadanos que estamos hartos de que nos gobiernen en Andaluc\xeda los sociolisto'), (datetime.datetime(2015, 12, 7, 17, 56, 56), u'rosalia_agudin', u"Ciudadanos pone en marcha un 'crowdfunding': por 500 euros puedes ser por un d\xeda dirigente de Rivera https://t.co/aDeLwsf9po v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 17, 55, 13), u'_raulpina_', u"Ciudadanos inicia un 'crowdfunding': por 500\u20ac puedes ser por un d\xeda 'dirigente' de Albert Rivera https://t.co/e7I3faDyLX v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 17, 43, 37), u'alvaromc27', u'@elmundoes cuando en este pa\xeds los ciudadanos elegiremos directament a nuestros presidentes o alcaldes  y no los partidos pol\xedticos'), (datetime.datetime(2015, 12, 7, 17, 34, 39), u'vaviol', u"Ciudadanos pone en marcha un 'crowdfunding': por 500 \u20ac puedes ser por 1 d\xeda dirigente d Albert Rivera https://t.co/bb3PnS8iIO v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 17, 32, 47), u'idearepuntoes', u"Ciudadanos pone en marcha un 'crowdfunding':  https://t.co/GW15Mt0tpo v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 17, 15, 4), u'Nuk_Nuik221', u'Reconozco que, aunque no sea fan de Ciudadanos, apoyo por completo el #YoTambienEstoyFondona  https://t.co/11n5umfxU4'), (datetime.datetime(2015, 12, 7, 16, 37, 9), u'elmundoes', u"RT @ElMundoEspana: El 'crowdfunding' de Ciudadanos: por 500 euros puedes ser por un d\xeda dirigente de Rivera  https://t.co/Nj8tvOfltk https:\u2026"), (datetime.datetime(2015, 12, 7, 16, 35, 57), u'Fernand76431025', u'@Inaki_Gil @elmundoes Me preocupa mucho que alguien que utiliza m\xe1s las entra\xf1as que el cerebro apoye a Ciudadanos'), (datetime.datetime(2015, 12, 7, 15, 56, 24), u'mariade73094493', u'@CiudadanosCs @Albert_Rivera @elmundoes Aaarriba ciudadanos!.\nCatalu\xf1a adelante!. https://t.co/Bpo0VE2J4O'), (datetime.datetime(2015, 12, 7, 13, 57, 41), u'inmapefe97', u'Ciudadanos financiar\xe1 la campa\xf1a con un cr\xe9dito del Banco Popular de 4 millones https://t.co/I1gJ3aUkC3 v\xeda @elmundoes'), (datetime.datetime(2015, 12, 7, 13, 30, 11), u'EspanaNaranja', u'@Yo_Ciudadanos @luciohergar \n\xa1\xa1Menudo par de narices que echan!!\n@Albert_Rivera @CsMadFuencarral @elmundoes @elpais_espana @abc @larazon_es'), (datetime.datetime(2015, 12, 7, 12, 42, 10), u'elmundomalaga', u"Moreno Bonilla (PP): 'Ciudadanos ha sustentado en Andaluc\xeda al gobierno de siempre' https://t.co/OHkFHVkvX9 v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 10, 36), u'Cs_Argamasilla', u"#ciudadanos Rivera: 'Si quedo segundo, yo ser\xe9 el l\xedder de la oposici\xf3n' https://t.co/q3XFV352D0 v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 10, 21, 31), u'MariaGilVitoria', u'Todos contra Ciudadanos https://t.co/2I9SkuEQC4 v\xeda @elmundoes'), (datetime.datetime(2015, 12, 7, 10, 1, 29), u'elmundopv', u'Todos contra Ciudadanos https://t.co/fJeI81d8to v\xeda @elmundoes'), (datetime.datetime(2015, 12, 7, 10, 0, 39), u'CsCiudadLineal', u".@Albert_Rivera 'Si quedo segundo, yo ser\xe9 el l\xedder de la oposici\xf3n' https://t.co/vnu01NHiAf v\xeda @elmundoes #Ciudadanos"), (datetime.datetime(2015, 12, 7, 9, 54, 35), u'CsAzuaga', u".@Albert_Rivera : 'Vamos a ganar a Mas en las urnas por primera vez' #Ciudadanos  https://t.co/FrmB1kk5h8 v\xeda @elmundoes"), (datetime.datetime(2015, 12, 7, 8, 0, 42), u'alvarotrece', u'Me alegro d la derrota de Maduro pero en cu\xe1ntas dictaduras los ciudadanos pueden dar una paliza as\xed al gobierno?\n https://t.co/86F6q3MaA1'), (datetime.datetime(2015, 12, 7, 7, 45, 41), u'bmazo', u'Esto debe cambiar @Ciudadanos\nhttps://t.co/fLJ4Bn1uJs v\xeda @elmundoes'), (datetime.datetime(2015, 12, 7, 7, 22, 4), u'anslorente', u'El @PPopular baja y @CiudadanosCs sube. Ciudadanos desgasta al PP en sus comunidades https://t.co/1SZr3RqnOy v\xeda @elmundoes')]

In [42]:
# ¿Cuantos tweets generan en un dia los tres periodicos (abc, el pais y el mundo) que sigue raspbebot?
tweets = []
for tweet in tweepy.Cursor(api.home_timeline, since="2015-12-06", until="2015-12-07").items():
    tweets.append(tweet)

print(len(tweets))


---------------------------------------------------------------------------
TweepError                                Traceback (most recent call last)
<ipython-input-42-1fdba0cda0d7> in <module>()
      1 # ¿Cuantos tweets generan en un dia los tres periodicos (abc, el pais y el mundo) que sigue raspbebot?
      2 tweets = []
----> 3 for tweet in tweepy.Cursor(api.home_timeline, since="2015-12-06", until="2015-12-07").items():
      4     tweets.append(tweet)
      5 

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/cursor.pyc in next(self)
    195         if self.current_page is None or self.page_index == len(self.current_page) - 1:
    196             # Reached end of current page, get the next page...
--> 197             self.current_page = self.page_iterator.next()
    198             self.page_index = -1
    199         self.page_index += 1

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/cursor.pyc in next(self)
    106 
    107         if self.index >= len(self.results) - 1:
--> 108             data = self.method(max_id=self.max_id, parser=RawParser(), *self.args, **self.kargs)
    109 
    110             if hasattr(self.method, '__self__'):

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/binder.pyc in _call(*args, **kwargs)
    241             return method
    242         else:
--> 243             return method.execute()
    244 
    245     # Set pagination mode

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/binder.pyc in execute(self)
    225                     raise RateLimitError(error_msg, resp)
    226                 else:
--> 227                     raise TweepError(error_msg, resp)
    228 
    229             # Parse the response payload

TweepError: {"errors":[{"message":"Rate limit exceeded","code":88}]}

In [43]:
len(tweets)


Out[43]:
272

In [47]:
print([(str(tweet.created_at),tweet.text) for tweet in tweets][-10:])


[('2015-12-07 08:15:13', u'Catalu\xf1a tribu a tribu https://t.co/eLYU2B22jM Por Salvador Sostres'), ('2015-12-07 08:10:52', u'RT @elpais_inter: Triunfo de la oposici\xf3n en las elecciones: Venezuela da la espalda al chavismo 17 a\xf1os despu\xe9s https://t.co/YZVwk1dWa2 Po\u2026'), ('2015-12-07 08:10:14', u'RT @ElMundoEnVivo: Europa despierta con el triunfo de la oposici\xf3n en #Venezuela y llegan las primeras reacciones.  https://t.co/PQdDlhuD94'), ('2015-12-07 08:09:20', u'Lo viejo de la pol\xedtica espa\xf1ola es para llorar, dice @JohnCarlin5, aunque hay razones para alegrarse https://t.co/JCGvewpPX2'), ('2015-12-07 08:05:07', u'Iglesias: \xabAhora que otros se quitan las corbatas quiz\xe1s es hora de que yo me la ponga\xbb https://t.co/TtR9nJg8Ic https://t.co/3lSAwItgJ1'), ('2015-12-07 08:03:31', u'RT @elpais_opinion: \xbfHabr\xe1 pel\xedculas de superh\xe9roes despu\xe9s de los pr\xf3ximos cinco a\xf1os? \xbfO ser\xe1n de h\xe9roes a secas? \xbfQu\xe9 dice Spielberg? ht\u2026'), ('2015-12-07 08:02:16', u'Puede que te hayas levantado sin tener muy claro si es fiesta en tu comunidad o no. Consulta el calendario laboral https://t.co/iIKdi1ifTn'), ('2015-12-07 08:02:06', u'RT @ElMundoEconomia: El informe de la #OMS que asociaba la carne con el c\xe1ncer hundi\xf3 las ventas casi un 10% https://t.co/B16R07Lr3t https:\u2026'), ('2015-12-07 07:55:04', u'Radiograf\xeda del hundimiento de la #Venezuela chavista https://t.co/ZBixA0Iby8 Por @fj_calero https://t.co/acNs01441o'), ('2015-12-07 07:54:49', u'\xbfLa derrota de Maduro en #Venezuela traer\xe1 un cambio de rumbo pol\xedtico en Latinoam\xe9rica? https://t.co/NxHDo28Z3c')]

Probando la libreria para streaming de tweets


In [ ]:
#Import the necessary methods from tweepy library
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import ConfigParser

config = ConfigParser.ConfigParser()
config.read('datosCuentaTwitter.ini')

APP_KEY = config.get('DatosTwitter','APP_KEY')
APP_SECRET = config.get('DatosTwitter','APP_SECRET')
OAUTH_TOKEN = config.get('DatosTwitter','OAUTH_TOKEN')
OAUTH_TOKEN_SECRET = config.get('DatosTwitter','OAUTH_TOKEN_SECRET')


class MyListener(StreamListener):
 
     ### ATENCION !!! Funcion desactualizada !!!!!
     ### Mirar codigo mas abajo para una version buena
    def on_data(self, data):  
        try:
            with open('python.json', 'a') as f:
                print(data)
                f.write(data)
                return True
        except BaseException as e:
            print("Error on_data: %s" % str(e))
        return True
 
    def on_error(self, status):
        print(status)
        return True

auth = tweepy.OAuthHandler(APP_KEY, APP_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    
twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track=['kevin'])

In [29]:
import thread
import json

#Import the necessary methods from tweepy library
import tweepy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream

#Variables that contains the user credentials to access Twitter API 
APP_KEY = 'XQqwUHk3iy8Wlk3JNMWjeM42D'
APP_SECRET = 'dD5B1Z7nc4cS2hvmoCo2qsZbqwCEOcI6yK94bqYfwhX9qjs4gQ'
OAUTH_TOKEN = '1635231295-upESx6zFjY0oVRjre9mBP3Hp6OA0krhEKWdD3a6'
OAUTH_TOKEN_SECRET = 'cFxHzCtlCSNmpnnQEBxAn6PXMDFcLR61J8vyKmrpmU'

periodicos = { 'elmundo':'14436030', 'elpais':'7996082', 'abc':'19923515','larazon':'112694236',
              'eldiarioes':'535707261','LaVanguardia':'74453123','publico':'17676713','20minutos':'31090827' ,
              'raspbebot':'1635231295' }

tweets = {}

class MyListener(StreamListener):
 
    def on_status(self, tweet):
        
        if tweet.user.screen_name in ['el_pais','elmundoes','abc_es','raspbebot']:
            print(tweet.created_at)
            print(tweet.user.screen_name)
            print(tweet.text)
            print(' *'*40)
            tweets.setdefault(tweet.user.screen_name,[]).append((str(tweet.created_at), tweet.text))
            
    def on_error(self, status_code):
        if status_code == 420:
            return False


auth = tweepy.OAuthHandler(APP_KEY, APP_SECRET)
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
    
twitter_stream = Stream(auth, MyListener())
twitter_stream.filter(track='PP,Psoe,Podemos,Ciudadanos,Rajoy,Pedro,Pablo,Albert, \
                             ,Mariano,Sanchez,Iglesias,Rivera, \
                             CiudadanosCs,PPopular,PSOE,ahorapodemos',
                      follow=[periodicos['elmundo'], periodicos['elpais'],periodicos['abc'],periodicos['larazon'], 
                              periodicos['eldiarioes'], periodicos['LaVanguardia'],periodicos['publico'],
                              periodicos['20minutos'],periodicos['raspbebot']] ) 



# Poner async=True para una ejecucion en paralelo
# Solo castellano languages=['es']

# Para seguir periodicos
#         [elmundo, elpais, abc, larazon,eldiarioes,LaVanguardia,publico,20minutos ,raspbebot]
# follow=['14436030', '7996082', '19923515', '112694236','535707261','74453123','17676713','31090827','1635231295']
# Termino de busqueda track=['dwwww']


2015-12-08 10:42:54
raspbebot
Iglesias Rivera
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-29-1be3c0ec1486> in <module>()
     43                       follow=[periodicos['elmundo'], periodicos['elpais'],periodicos['abc'],periodicos['larazon'], 
     44                               periodicos['eldiarioes'], periodicos['LaVanguardia'],periodicos['publico'],
---> 45                               periodicos['20minutos'],periodicos['raspbebot']] ) 
     46 
     47 

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/streaming.pyc in filter(self, follow, track, async, locations, stall_warnings, languages, encoding, filter_level)
    428         self.session.params = {'delimited': 'length'}
    429         self.host = 'stream.twitter.com'
--> 430         self._start(async)
    431 
    432     def sitestream(self, follow, stall_warnings=False,

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/streaming.pyc in _start(self, async)
    344             self._thread.start()
    345         else:
--> 346             self._run()
    347 
    348     def on_closed(self, resp):

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/streaming.pyc in _run(self)
    253                     self.snooze_time = self.snooze_time_step
    254                     self.listener.on_connect()
--> 255                     self._read_loop(resp)
    256             except (Timeout, ssl.SSLError) as exc:
    257                 # This is still necessary, as a SSLError can actually be

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/streaming.pyc in _read_loop(self, resp)
    305                     raise TweepError('Expecting length, unexpected value found')
    306 
--> 307             next_status_obj = buf.read_len(length)
    308             if self.running:
    309                 self._data(next_status_obj)

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/tweepy/streaming.pyc in read_len(self, length)
    159                 return self._pop(length)
    160             read_len = max(self._chunk_size, length - len(self._buffer))
--> 161             self._buffer += self._stream.read(read_len)
    162 
    163     def read_line(self, sep='\n'):

/home/dj/anaconda3/envs/py2/lib/python2.7/site-packages/requests/packages/urllib3/response.pyc in read(self, amt, decode_content, cache_content)
    280             else:
    281                 cache_content = False
--> 282                 data = self._fp.read(amt)
    283                 if amt != 0 and not data:  # Platform-specific: Buggy versions of Python.
    284                     # Close the connection when no data is returned

/home/dj/anaconda3/envs/py2/lib/python2.7/httplib.pyc in read(self, amt)
    586 
    587         if self.chunked:
--> 588             return self._read_chunked(amt)
    589 
    590         if amt is None:

/home/dj/anaconda3/envs/py2/lib/python2.7/httplib.pyc in _read_chunked(self, amt)
    655                 return ''.join(value)
    656             else:
--> 657                 value.append(self._safe_read(chunk_left))
    658                 amt -= chunk_left
    659 

/home/dj/anaconda3/envs/py2/lib/python2.7/httplib.pyc in _safe_read(self, amt)
    701         s = []
    702         while amt > 0:
--> 703             chunk = self.fp.read(min(amt, MAXAMOUNT))
    704             if not chunk:
    705                 raise IncompleteRead(''.join(s), amt)

/home/dj/anaconda3/envs/py2/lib/python2.7/socket.pyc in read(self, size)
    382                 # fragmentation issues on many platforms.
    383                 try:
--> 384                     data = self._sock.recv(left)
    385                 except error, e:
    386                     if e.args[0] == EINTR:

/home/dj/anaconda3/envs/py2/lib/python2.7/ssl.pyc in recv(self, buflen, flags)
    732                     "non-zero flags not allowed in calls to recv() on %s" %
    733                     self.__class__)
--> 734             return self.read(buflen)
    735         else:
    736             return self._sock.recv(buflen, flags)

/home/dj/anaconda3/envs/py2/lib/python2.7/ssl.pyc in read(self, len, buffer)
    619                 v = self._sslobj.read(len, buffer)
    620             else:
--> 621                 v = self._sslobj.read(len or 1024)
    622             return v
    623         except SSLError as x:

KeyboardInterrupt: 

In [22]:
print(tweets)


{u'raspbebot': [('2015-12-08 10:11:44', u'Albert que bonico')]}

In [23]:
with open('periodicos.json', 'a') as f:
    datos = json.dumps(tweets, sort_keys=True, indent=4, separators=(',',':'))
    f.write(datos)

In [ ]: