domingo, 9 de agosto de 2020

Lendo tabelas HTML com pandas

Photo by Artem Sapegin on Unsplash

Um uso pouco conhecido da biblioteca pandas é a sua capacidade de ler tabelas de um site da web. Com pandas é fácil obter dados de uma tabela num site da web como a Wikipédia.
Nesse tutorial vamos obter dados de uma página na Wikipédia. Esses dados são das musicas de Avril Lavgine que foram utilizadas em séries.

Como ler dados de uma tabela HTML com pandas

Primeiro vamos chamar o método read_html(). Esse método carrega todas as tabelas de um arquivo html. Esse arquivo pode estar na internet ou no seu computador.

>>> import pandas as pd
>>> url = 'https://pt.wikipedia.org/wiki/Discografia_de_Avril_Lavigne'
>>> tabelas = pd.read_html(url)
>>> len(tabelas)
27

Com o código acima carregamos todas as tabelas no objeto tabelas. Com isso já podemos procurar pela tabela que queremos. Podemos acessar cada tabela com um índice do objeto tabela. A tabela que contem uma lista com as músicas que foram usados em séries é a 16.

>>> tabelas[16]
          Ano  ...   Ref.
0   2002/2004  ...  [108]
1   2002/2004  ...  [108]
2   2002/2004  ...  [108]
3        2003  ...  [108]
4        2003  ...  [108]
5        2003  ...  [108]
6        2003  ...  [108]
7        2003  ...  [108]
8        2004  ...  [108]
9        2004  ...  [108]
10       2005  ...  [108]
11       2005  ...  [108]
12  2007/2008  ...  [108]
13  2007/2008  ...  [108]
14  2007/2008  ...  [108]
15  2007/2008  ...  [108]
16  2007/2008  ...  [108]
17  2007/2008  ...  [108]
18  2007/2008  ...  [108]
19  2007/2008  ...  [108]
20       2008  ...  [108]
21       2008  ...  [108]
22       2008  ...  [108]
23       2008  ...  [108]
24  2008/2009  ...  [108]
25  2008/2009  ...  [108]
26       2009  ...  [108]
27       2009  ...  [108]

[28 rows x 5 columns]

Procurar por índice pode ser uma tarefa trabalhosa, especialmente se a pagina tiver muitas tabelas. Um jeito de encurtar a busca é carregar apenas a tabela que queremos. Podemos fazer isso identificando a tabela que nos interessa de algum modo. No exemplo abaixo vamos identificar a tabela pelo conteúdo da tag <caption>.

>>> url2 = 'https://en.wikipedia.org/wiki/The_Beatles_discography'
>>> beatles = pd.read_html(url2, match='List of studio albums', na_values='-')
>>> beatles
[                                                Title  ...                                     Certifications
                                                Title  ...                                     Certifications
0                                    Please Please Me  ...  BPI: Gold[10] ARIA: Gold[11] MC: Gold[12] RIAA...
1                                 With the Beatles[B]  ...  BPI: Gold[10] ARIA: Gold[11] BVMI: Gold[14] MC...
2                          Introducing... The Beatles  ...                                 RIAA: Platinum[13]
3                                   Meet the Beatles!  ...             MC: Platinum[12] RIAA: 5× Platinum[13]
4                                     Twist and Shout  ...                                MC: 3× Platinum[12]
5                           The Beatles' Second Album  ...             MC: Platinum[12] RIAA: 2× Platinum[13]
6                        The Beatles' Long Tall Sally  ...                                       MC: Gold[12]
7                                  A Hard Day's Night  ...             MC: Platinum[12] RIAA: 4× Platinum[13]
8                                  A Hard Day's Night  ...                   BPI: Platinum[10] ARIA: Gold[11]
9                                       Something New  ...                 MC: Gold[12] RIAA: 2× Platinum[13]
10                                   Beatles for Sale  ...  BPI: Gold[10] ARIA: Gold[11] MC: Gold[12] RIAA...
11                                        Beatles '65  ...             MC: Platinum[12] RIAA: 3× Platinum[13]
12                                         Beatles VI  ...                    MC: Gold[12] RIAA: Platinum[13]
13                                              Help!  ...                   BPI: Platinum[10] ARIA: Gold[11]
14                                              Help!  ...          MC: 2× Platinum[12] RIAA: 3× Platinum[13]
15                                        Rubber Soul  ...  BPI: Platinum[10] ARIA: Platinum[11] BVMI: Gol...
16                                        Rubber Soul  ...          MC: 2× Platinum[12] RIAA: 6× Platinum[13]
17                                Yesterday and Today  ...             MC: Platinum[12] RIAA: 2× Platinum[13]
18                                           Revolver  ...            BPI: 2× Platinum[10] ARIA: Platinum[11]
19                                           Revolver  ...          MC: 2× Platinum[12] RIAA: 5× Platinum[13]
20              Sgt. Pepper's Lonely Hearts Club Band  ...  BPI: 17× Platinum[10] ARIA: 4× Platinum[11] BV...
21                               Magical Mystery Tour  ...  BPI: Platinum[10] ARIA: Platinum[11] MC: 4× Pl...
22                    The Beatles ("The White Album")  ...  BPI: 2× Platinum[10] ARIA: 2× Platinum[11] MC:...
23                                Yellow Submarine[D]  ...      BPI: Gold[10] MC: Gold[12] RIAA: Platinum[13]
24                                         Abbey Road  ...  BPI: 3× Platinum[10] ARIA: 3× Platinum[11] BVM...
25                                          Let It Be  ...  BPI: Platinum[10] ARIA: Platinum[11] MC: 3× Pl...
26  "—" denotes that the recording did not chart o...  ...  "—" denotes that the recording did not chart o...

[27 rows x 10 columns]]

O parâmetro match especifica que queremos todas as tabelas que tenha a string que passamos para o parâmetro. Nessa pagina apenas uma tabela tinha a string, se tivesse mais elas seriam carregadas também. Outro jeito de especificar uma tabela é pelos atributos das tags HTML. Podemos procurar por atributo e valor do atributo. Por exemplo, se quiséssemos uma tabela cujo valor do atributo id seja tabela1, passaríamos o dicionario {'id':'tabela1'} para o parâmetro attrs. Podemos utilizar qualquer atributo e qualquer valor.

>>> tabela = pd.read_html(url, attrs={'class':'infobox_v2'})
>>> tabela
[   Discografia de Avril Lavigne Discografia de Avril Lavigne.1
0            Avril em Amsterdam             Avril em Amsterdam
1             Álbuns de estúdio                              6
2                Álbuns ao vivo                              4
3          Álbuns de compilação                              2
4               Álbuns de vídeo                              5
5           Extended plays (EP)                              4
6                       Singles                             25
7                       Lados B                             13
8               Vídeos musicais                             16
9             Álbuns de tributo                              1
10                 Vídeo single                              2
11                       Covers                             10
12            Álbuns de remixes                              2]

Nesse exemplo, carregamos todas as tabelas com o valor infobox_v2 atribuído ao atributo class. Nessa página, apenas uma tabela contem o valor infobox_v2 atribuído ao atributo class.

Como funciona o método read_html()

O método read_html() retorna uma lista com dataframes pandas. Para cada tabela encontrada na página um dataframe é criado.

Referência:
Método read_html()

0 comentários:

Postar um comentário