2015-01-08 14 views
6

Tôi cố gắng để tải dữ liệu wikipedia về Mỹ tối cao phán Tòa án vào R:Nạo một bảng HTML phức tạp thành một data.frame trong 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" 

Vấn đề là các dữ liệu bị thay đổi. Thay vì tên xuất hiện như thế nào tôi nhìn thấy nó trong bảng HTML thực tế ("James Wilson"), nó thực sự xuất hiện hai lần, một lần là "LastName, Firstname" và sau đó một lần nữa là "Firstname LastName".

Lý do là mỗi thực sự chứa vô hình:

<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> 

Quy định này cũng đúng đối với các cột có dữ liệu số. Tôi đoán rằng mã bổ sung này là cần thiết để phân loại bảng HTML. Tuy nhiên, tôi chưa rõ làm thế nào để loại bỏ những nhịp khi cố gắng để tạo ra một data.frame từ bảng trong R.

Trả lời

8

Có thể như thế này

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

Bạn có thể sử dụng 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() 

Đó không phải là hoàn hảo, do đó bạn có thể muốn tinh chỉnh css bộ chọn nhưng nó giúp bạn khá gần.

Các vấn đề liên quan