2015-10-04 46 views
0

我想網絡刮(波蘭)Wikipedia categories的名稱,以樹的形式給R列表,保持樹的結構。如何在樹的形式下將樹刮到R列表中?

我的想法是將所有類別放入列表中,其中子列表將指示該類別的子類別。問題是我不知道如何讓刮進最骯髒的孩子。

我現在所擁有的是樹的某些級別的單獨列表,但它似乎並不是最佳解決方案。另外,我會先查找鏈接,然後再查看兩個類別(幾乎)完全相同的類別的名稱。

這是我寫到目前爲止代碼:

library("stringi") 
library("rvest") 

find_links <- function(link){ 
    strona <- read_html(link) 
    kategorie <- html_nodes(strona, ".CategoryTreeLabel") 
    if(length(kategorie)==0) return(NA) 
    as.list(stri_paste("http://pl.wikipedia.org", html_attr(kategorie, "href"))) 
} 

find_titles <- function(link){ 
    strona <- read_html(link) 
    kategorie <- html_nodes(strona, ".CategoryTreeLabel") 
    if(length(kategorie)==0) return(NA) 
    as.list(html_text(kategorie)) 
} 

link <- 'http://pl.wikipedia.org/wiki/Wikipedia:Drzewo_kategorii' 
strona <- read_html(link) 
kategorie <- html_nodes(strona, ".CategoryTreeLabel")[-c(1:10, 14, 69, 96, 101, 155, 176, 188, 220, 234)] //don't need these categories 
kategorie <- kategorie[220:225] //taking a sample so it doesn't take long 
linki <- as.list(stri_paste("http://pl.wikipedia.org", html_attr(kategorie, "href"))) 
tytuly <- as.list(html_text(kategorie)) 
tytuly <- list(tytuly, linki) 


aa <- rapply(linki, find_links, how = 'replace') 
aa1 <- rapply(linki, find_titles, how = 'replace') 
bb <- rapply(aa, find_links, how = 'replace') 
bb1 <- rapply(aa, find_titles, how = 'replace') 
... 

這裏是BB1結果(樹的第二級):

> bb1 
[[1]] 
[[1]][[1]] 
[1] NA 

[[1]][[2]] 
[[1]][[2]][[1]] 
[1] "Odznaczenia Związku Ochotniczych Straży Pożarnych Rzeczypospolitej Polskiej" 


[[1]][[3]] 
[1] NA 

[[1]][[4]] 
[[1]][[4]][[1]] 
[1] "Pożary według państw" 

請幫助。我願意接受任何其他能夠保持類別結構的解決方案。

回答

1

事情是這樣的:

library(stringi) 
library(rvest) 
library(dplyr) 

expand_tree = function(link, level) { 
    print(link) 

    tree_nodes = 
    link %>% 
    read_html %>% 
    html_nodes(".CategoryTreeLabel") 

    if (length(tree_nodes) > 0) 
    data_frame(link = 
       tree_nodes %>% 
       html_attr("href") %>% 
       paste0("http://pl.wikipedia.org", .), 
       name = html_text(tree_nodes)) %>% 
    setNames(names(.) %>% paste(level, . , sep = ".")) else data_frame() } 

level1 = 
    'http://pl.wikipedia.org/wiki/Wikipedia:Drzewo_kategorii' %>% 
    expand_tree("level1") %>% 
    slice(-c(1:10, 14, 69, 96, 101, 155, 176, 188, 220, 234)) %>% 
    slice(220:225) 

level2 = 
    level1 %>% 
    group_by(level1.link) %>% 
    do(expand_tree(first(.$level1.link), "level2")) %>% 
    ungroup 

level3 = 
    level2 %>% 
    group_by(level2.link) %>% 
    do(expand_tree(first(.$level2.link), "level3")) %>% 
    ungroup