2015-01-08 17 views
6

Sto cercando di caricare i dati di Wikipedia con US giudici della Corte Suprema in R:raschiando una tabella HTML complesso in un data.frame in R

library(rvest) 

html = html("http://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States") 
judges = html_table(html_nodes(html, "table")[[2]]) 
head(judges[,2]) 

[1] "Wilson, JamesJames Wilson"  "Jay, JohnJohn Jay†"    
[3] "Cushing, WilliamWilliam Cushing" "Blair, JohnJohn Blair, Jr."  
[5] "Rutledge, JohnJohn Rutledge"  "Iredell, JamesJames Iredell" 

Il problema è che i dati non è valido. Piuttosto che il nome che appare come lo vedo nella tabella HTML reale ("James Wilson"), in realtà appare due volte, una volta come "Cognome, Nome" e poi ancora come "Nome Cognome".

La ragione è che ogni realtà contiene un invisibile:

<td style="text-align:left;" class=""> 
    <span style="display:none" class="">Wilson, James</span> 
    <a href="/wiki/James_Wilson" title="James Wilson">James Wilson</a> 
</td> 

Lo stesso vale anche per le colonne con dati numerici. Sto indovinando che questo codice aggiuntivo è necessario per l'ordinamento della tabella HTML. Tuttavia, sono poco chiaro come rimuovere quelle campate quando si cerca di creare un data.frame dalla tabella in R.

risposta

8

Forse come questo

library(XML) 
library(rvest) 
html = html("http://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States") 
judges = html_table(html_nodes(html, "table")[[2]]) 
head(judges[,2]) 
# [1] "Wilson, JamesJames Wilson"  "Jay, JohnJohn Jay†"    "Cushing, WilliamWilliam Cushing" "Blair, JohnJohn Blair, Jr."  
# [5] "Rutledge, JohnJohn Rutledge"  "Iredell, JamesJames Iredel 

removeNodes(getNodeSet(html, "//table/tr/td[2]/span")) 
judges = html_table(html_nodes(html, "table")[[2]]) 
head(judges[,2]) 
# [1] "James Wilson" "John Jay†"  "William Cushing" "John Blair, Jr." "John Rutledge" "James Iredell" 
4

si potrebbe usare rvest

library(rvest) 

html("http://en.wikipedia.org/wiki/List_of_Justices_of_the_Supreme_Court_of_the_United_States")%>% 
    html_nodes("span+ a") %>% 
    html_text() 

Non è perfetto così si potrebbe desiderare di perfezionare il css selettore ma ti avvicina abbastanza.

Problemi correlati