11

Click here to load reader

Twitter and Youtube Collector

Embed Size (px)

Citation preview

Page 1: Twitter and Youtube Collector

Universidade Federal de Ouro Preto

Instituto de Ciências Exatas e Biológicas

Departamento de Computação

BCC428 - ANÁLISE DE MÍDIA SOCIALSegundo Trabalho Prático

Johnnatan Messias

Pollyanna Gonçalves

Wellington Dores

Professor - Fabricio Benevenuto

Ouro Preto

10 de outubro de 2011

Page 2: Twitter and Youtube Collector

Sumário

0.1 Considerações iniciais . . . . . . . . . . . . . . . . . . . . . . . . . . . 10.2 Especi�cação do problema . . . . . . . . . . . . . . . . . . . . . . . . 1

1 Problemas 1

1.1 Coletor Timeline Pública - Twitter . . . . . . . . . . . . . . . . . . . 11.2 Coletor Timeline de Usuário - Twitter . . . . . . . . . . . . . . . . . . 21.3 Coletor de Pro�le - Twitter . . . . . . . . . . . . . . . . . . . . . . . 31.4 Coletor de Followers - Twitter . . . . . . . . . . . . . . . . . . . . . . 41.5 Coletor de Friends - Twitter . . . . . . . . . . . . . . . . . . . . . . . 41.6 Coletor da Quantidade de Seguidores e Seguidos - Twitter . . . . . . 51.7 Coletor do Youtube . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.8 Funções Auxiliares . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.9 Função Principal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2 Limitações 7

3 Testes 8

4 Referências 9

Lista de Figuras

1 Função getUserProfile . . . . . . . . . . . . . . . . . . . . . . . . . 82 Função getT imeLinePublic . . . . . . . . . . . . . . . . . . . . . . . 83 Função getFollowersAndFriendsCount . . . . . . . . . . . . . . . . 94 Função mostPopularY outube . . . . . . . . . . . . . . . . . . . . . . 9

Listings

1 Coletor da timeline Pública . . . . . . . . . . . . . . . . . . . . . . . 22 Coletor da timeline de um usuário . . . . . . . . . . . . . . . . . . . . 23 Coletor da timeline de um pro�le . . . . . . . . . . . . . . . . . . . . 34 Coletor de followers . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 Coletor de friends . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 Coletor da quantidade de seguidores e seguidos . . . . . . . . . . . . . 57 Coletor do Youtube . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 Funções Auxiliares . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69 Função Principal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2

Page 3: Twitter and Youtube Collector

0.1 Considerações iniciais

• Linguagem utilizada: Linguagem Python.

• Ambiente de desenvolvimento da documentação: TeXnicCenter 1 BETA 7.50-Editor de LATEX.

0.2 Especi�cação do problema

Este trabalho tem como objetivo exercitar formas de coletar dados de redes sociasonline através de suas respectivas APIs e o entendimento das mesmas.

1 Problemas

• Construa um coletor de dados do Twitter em Python. Seu programa devereceber como parâmetro o ID de um usuário e deve então coletar informaçõesdo per�l do usuário, dos tweets já postados pelo usuário (caso a conta não sejaprivada) e a lista de seguidores e seguidos.

• Desenvolva um crawler que faça a coleta de uma amostra aleatória de tweetsa partir da API de streaming.

• Desenvolva um coletor de informações da API de outro sistema que não o jáapresentado.

As funções abaixo apresentam uma resolução para os problemas propostosacima:

1.1 Coletor Timeline Pública - Twitter

Através dessa funções é possível capturar os dados referentes a TimeLinePública do Twitter.

Para isso, é necessário acessar a API do Twitter e capturar como, por exemplo,estes dados:

1. Tweet:

� Text: o Tweet do usuário.

� Created At: Data de criação do Tweet.

� Place: Cidade e país de origem do Tweet.

� ID: Número de identi�cação do Tweet.

� User: Usuário proprietário do Tweet.

2. User:

� Name: Nome de registro do usuário.

� Description: Descrição do per�l do usuário.

� ID: Número de identi�cação do usuário.

� Location: Coordenadas geográ�cas do usuário.

1

Page 4: Twitter and Youtube Collector

1 de f getTimeLinePubl ic ( ) :u r l = " https : // api . tw i t t e r . com/1/ s t a t u s e s / pub l i c_t ime l ine . j son

? count=3"3 d = getJson ( u r l )

5 l = [ ]

7 f o r i in range ( l en (d) ) :i f (d [ i ] [ ' p l ace ' ] == None) :

9 p lace = "Place not e x i s t s "e l s e :

11 p lace = (d [ i ] [ ' p l ace ' ] [ ' full_name ' ] + " − "+d [ i ] [ 'p l ace ' ] [ ' country ' ] )

l . append ( "\nMessage %d" %i )13 l . append ( " Text : %s " %(d [ i ] [ ' t ex t ' ] ) )

l . append ( " Created At : %s " %(d [ i ] [ ' created_at ' ] ) )15 l . append ( " Place : %s " %(p lace ) )

l . append ( " ID : %s" %(d [ i ] [ ' id ' ] ) )17 l . append ( " User : @%s" %(d [ i ] [ ' u se r ' ] [ ' screen_name '

] ) )l . append ( " Name : %s " % (d [ i ] [ ' use r ' ] [ 'name '

] ) )19 l . append ( " Desc r ip t i on : %s " % (d [ i ] [ ' use r '

] [ ' d e s c r i p t i o n ' ] ) )l . append ( " ID : %s" % (d [ i ] [ ' use r ' ] [ ' id ' ] ) )

21 l . append ( " Locat ion : %s " % (d [ i ] [ ' u se r ' ] [ 'l o c a t i o n ' ] ) )

23 printMyList ( l )

Listing 1: Coletor da timeline Pública

1.2 Coletor Timeline de Usuário - Twitter

Semalhando à seção 1.1, aqui capturamos a lista de Tweets de um determinadousuário.

� Text: Tweet do usuário.

� Created At: Data de criação do Tweet.

� Place: Cidade e país de origem do Tweet.

1 de f getTimeLineUser ( id ) :u r l = " https : // tw i t t e r . com/ s t a t u s e s / user_t ime l ine . j son ? user_id

=" + s t r ( id )3 d = getJson ( u r l )

l = [ ]5

i f ( l en (d) == 0) :7 l . append ( "TimeLineUser not found or not e x i s t s " )

re turn9

f o r i in range ( l en (d) ) :11 i f (d [ i ] [ ' p l ace ' ] == None ) :

p lace = "Place not e x i s t s "

2

Page 5: Twitter and Youtube Collector

13 e l s e :p lace = (d [ i ] [ ' p l ace ' ] [ ' full_name ' ] + " − "+d [ i ] [ '

p l ace ' ] [ ' country ' ] )15 l . append ( "\nMessage %d" %i )

l . append ( " Text : %s " %(d [ i ] [ ' t ex t ' ] ) )17 l . append ( " Created At : %s " %(d [ i ] [ ' created_at ' ] ) )

l . append ( " Place : %s " %(p lace ) )19

printMyList ( l )

Listing 2: Coletor da timeline de um usuário

1.3 Coletor de Pro�le - Twitter

Função responsável por obter os seguintes dados de um determinado usuário:

� User: Usuário proprietário do Tweet.

� Name: Nome de registro do usuário.

� Status: Último Tweet postado pelo usuário.

� Description: Descrição do per�l do usuário.

� Followers Count: Quantidade de seguidores.

� Friends Count: Quantidade dde seguidos.

� Listed Count: Quantidade de listas do usuário.

� Veri�ed: Informa se a conta do usuário foi veri�cada.

� Language: Idioma utilizado pelo usuário.

� URL: Exibe a URL que o usuário de�niu no seu pro�le.

� Location: Coordenadas geográ�cas do usuário.

de f g e tU s e rP r o f i l e ( id ) :2 u r l = " https : // api . tw i t t e r . com/1/ use r s /show . j son ?

i n c l ud e_en t i t i e s=true&user_id=" + s t r ( id )d = getJson ( u r l )

4 s t a tu s = None

6 l = [ ]

8 i f ( l en (d) == 0) :l . append ( "User not found or not e x i s t s " )

10 re turni f (d . has_key ( ' s t a tu s ' ) ) :

12 s t a tu s = d [ ' s t a tu s ' ] [ ' t ex t ' ]

14 l . append ( "User @%s : " %d [ ' screen_name ' ] )l . append ( " Name : %s " %d [ 'name ' ] )

16 l . append ( " Status : %s " %s ta tu s )l . append ( " Desc r ip t i on : %s " %d [ ' d e s c r i p t i o n ' ] )

18 l . append ( " Fo l lowers Count : %s " %d [ ' fo l l owers_count ' ] )l . append ( " Fr iends Count : %s " %d [ ' f r i ends_count ' ] )

20 l . append ( " L i s t ed Count : %s " %d [ ' l i s t ed_count ' ] )l . append ( " Ve r i f i e d : %s " %d [ ' v e r i f i e d ' ] )

3

Page 6: Twitter and Youtube Collector

22 l . append ( " Language : %s " %d [ ' lang ' ] )l . append ( " Url : %s " %d [ ' u r l ' ] )

24 l . append ( " Locat ion : %s " %d [ ' l o c a t i o n ' ] )

26 printMyList ( l )

Listing 3: Coletor da timeline de um pro�le

1.4 Coletor de Followers - Twitter

Aqui capturamos a lista de Seguidores(Followers) de um determinado usuário.

É importante ressaltar que a cada captura nos é fornecido, através da API doTwitter, uma lista de 5000 IDs dos usuários. Logo foi realizado um tratamentode modo a obter toda a lista do utuário que ultrapasse esse limite.

de f getFo l lowersUser ( id ) :2 cur so r = −1

count = 14 n = 5000

nFol lowers = getFol lowersAndFriendsCount ( id ) [ 0 ]6 qn tL i s t s = in t (math . c e i l ( f l o a t ( nFol lowers ) /n) )

8 f o r i in range ( qn tL i s t s ) :l = [ ]

10 u r l = " https : // api . tw i t t e r . com/1/ f o l l ow e r s / i d s . j son ? cur so r="+s t r ( cur so r )+"&user_id=" + s t r ( id )

d = getJson ( u r l )12 i f ( l en (d [ ' i d s ' ] ) == 0) :

l . append ( "User doesn ' t have f o l l ow e r s " )14 re turn

16 f o r i in range ( l en (d [ ' i d s ' ] ) ) :l . append ( s t r ( count )+"/"+s t r ( nFol lowers ) )

18 l . append ( "ID : %s " %d [ ' i d s ' ] [ i ] )count = count + 1

20 printMyList ( l )cu r so r = d [ ' next_cursor ' ]

Listing 4: Coletor de followers

1.5 Coletor de Friends - Twitter

Aqui capturamos a lista de Seguidos(Friends) de um determinado usuário.

A execução dessa função é semelhante à 1.4.

1 de f getFr iendsUser ( id ) :cu r so r = −1

3 count = 1n = 5000

5 nFriends = getFol lowersAndFriendsCount ( id ) [ 1 ]qn tL i s t s = in t (math . c e i l ( f l o a t ( nFriends ) /n) )

7f o r i in range ( qn tL i s t s ) :

4

Page 7: Twitter and Youtube Collector

9 l = [ ]u r l = " https : // api . tw i t t e r . com/1/ f r i e n d s / i d s . j son ? cur so r="

+s t r ( cur so r )+"&user_id=" + s t r ( id )11 d = getJson ( u r l )

13 i f ( l en (d [ ' i d s ' ] ) == 0) :l . append ( "User doesn ' t have f r i e n d s " )

15 re turn

17 f o r i in range ( l en (d [ ' i d s ' ] ) ) :l . append ( s t r ( count )+"/"+s t r ( nFriends ) )

19 l . append ( "ID : %s " %d [ ' i d s ' ] [ i ] )count = count + 1

21printMyList ( l )

23 cur so r = d [ ' next_cursor ' ]

Listing 5: Coletor de friends

1.6 Coletor da Quantidade de Seguidores e Seguidos -

Twitter

Essa função é responsável por de�nir a quantidade de Seguidores e Seguidos deum determinado usuário para uso exclusivo das funções 1.4 e 1.5. Basicamenteretorna uma tupla contendo o número de Seguidores e Seguidos.

1 de f getFollowersAndFriendsCount ( id ) :u r l = " https : // api . tw i t t e r . com/1/ use r s /show . j son ?

i n c l ud e_en t i t i e s=true&user_id=" + s t r ( id )3 d = getJson ( u r l )

i f ( l en (d) == 0) :5 p r i n t "User doesn ' t have f o l l ow e r s "

re turn 07 return (d [ ' f o l l owers_count ' ] , d [ ' f r i ends_count ' ] )

Listing 6: Coletor da quantidade de seguidores e seguidos

1.7 Coletor do Youtube

O coletor para o Y outube apresentado abaixo retorna uma lista dos vídeosmais populares da rede, incluindo suas descrições e categorias:

� Categoria: Exibe a categoria dos vídeos capturados.

� Title: Título do vídeo.

� Autor: Autor do vídeo.

� Published: Data de publicação do vídeo no Youtube

1 de f most_popular_Youtube ( ) :l = [ ]

3 u r l = ( "http :// gdata . youtube . com/ f e ed s / api / s tandard f eeds /most_popular ?v=2&a l t=j son " )

5

Page 8: Twitter and Youtube Collector

d = getJson ( u r l )5 j son = d [ ' f e ed ' ]

v ideos = j son [ ' entry ' ]7

f o r i in range ( l en ( v ideos ) ) :9 v i d eoL i s t = v ideos [ i ]

l . append ( "Categor ia : " + v id eoL i s t [ ' category '] [ 1 ] [ ' l a b e l ' ] )

11 l . append ( " T i t l e : " + v id eoL i s t [ ' t i t l e ' ] [ ' $t' ] )

l . append ( " Autor : " + v id eoL i s t [ ' author '] [ 0 ] [ 'name ' ] [ ' $t ' ] )

13 l . append ( " Publ ished : " + v ideoL i s t [ ' pub l i shed '] [ ' $t ' ] )

15 printMyList ( l )

Listing 7: Coletor do Youtube

1.8 Funções Auxiliares

Estas são funções importantes para a entrada e saída dos dados.

Temos:

� getJson: Função responsável por armazenar o mapa do JSon retornadopela API do Twitter.

� printMyList: Função responsável pela impressão em tela dos resultadosobtidos em cada uma das execuções das funções do programa.

1 de f getJson ( u r l ) :arq = u r l l i b . ur lopen ( u r l )

3 re turn ( j son . load ( arq ) )

5 de f pr intMyList ( l ) :f o r i in range ( l en ( l ) ) :

7 p r i n t l [ i ]

Listing 8: Funções Auxiliares

1.9 Função Principal

Essa é a função principal do programa. É nela em que o usuário de�ne o ciclode execução de todo o programa.

Vide código 9.

1 de f ge tPa ine l ( ) :p r i n t ( " [ 0 ] − Exit " )

3 p r i n t ( " [ 1 ] − getTimeLinePubl ic " )p r i n t ( " [ 2 ] − getTimeLineUser " )

5 p r i n t ( " [ 3 ] − g e tU s e rP r o f i l e " )p r i n t ( " [ 4 ] − getFo l lowersUser " )

7 p r i n t ( " [ 5 ] − getFr iendsUser " )

6

Page 9: Twitter and Youtube Collector

pr in t ( " [ 6 ] − getFol lowersAndFriendsCount " )9 p r in t ( " [ 7 ] − Videos mais populares do Youtube" )

11 de f main ( ) :whi l e (True ) :

13 ge tPa ine l ( )op = input ( " D ig i t e a opcao : " )

15i f ( op == 0) :

17 break

19 e l i f ( op == 1) :getTimeLinePubl ic ( )

21 e l i f ( op == 7) :most_popular_Youtube ( )

23e l s e :

25 id = input ( " D ig i t e o ID do User : " )i f ( op == 2) :

27 getTimeLineUser ( id )e l i f ( op == 3) :

29 g e tU s e rP r o f i l e ( id )e l i f ( op == 4) :

31 getFo l lowersUser ( id )e l i f ( op == 5) :

33 getFr iendsUser ( id )e l i f ( op == 6) :

35 count = getFollowersAndFriendsCount ( id )p r i n t ( " Fo l lowers Count : %s " %count [ 0 ] )

37 p r in t ( " Fr iends Count : %s " %count [ 1 ] )

39 i f __name__ == "__main__" :main ( )

Listing 9: Função Principal

2 Limitações

Nesse Trabalho Prático tivemos como di�culdade em utilizar caracteres unicodeno Windows, sendo assim, sugiro a execução do programa no Sistema OperacionalLinux ou Mac uma vez que não tivemos problemas em executar nessas plataformas.

7

Page 10: Twitter and Youtube Collector

3 Testes

Abaixo estão representados os testes de funcionamento das funções getUserPro�le(Figura 1), getTimeLinePublic (Figura 2), getFollowersAndFriendsCount (Figura3) e mostPopularYoutube (Figura 4).

Figura 1: Função getUserProfile

Figura 2: Função getT imeLinePublic

8

Page 11: Twitter and Youtube Collector

Figura 3: Função getFollowersAndFriendsCount

Figura 4: Função mostPopularY outube

4 Referências

• "`A python wrapper around the Twitter API"' -http://code.google.com/p/python-twitter/

• "`Twitter Developers"' -https://dev.twitter.com/

• "`APIs e Ferramentas do Youtube"' -http://code.google.com/intl/pt-BR/apis/youtube/overview.html

9