多好的问题啊.您只获得表的第一行,因为这是页面最初加载的全部内容,并且在后台发生了一些JavaScript魔术,可以在页面加载后加载表的其余部分.如果你重新加载页面并仔细观察,你就会看到这种情况——我在下面添加了一个gif来显示这一点.因为R没有运行所有这些额外的魔法,所以它得到的只是原始页面.
然而,所有这一切意味着我们需要寻找一个不同的URL来获取整个表.使用Chrome的开发工具,我们了解到该表来自https://www.wikidata.org/wiki/Special:EntityData/Q3044.json,这是我们真正想要刮取的页面.如果我们用jsonLite
下载它,我们不能得到准确的表格,但我们可以用dplyr
个工具重新组装它.下面是一段代码:
wiki_data <- jsonlite::read_json("https://www.wikidata.org/wiki/Special:EntityData/Q3044.json")
table_data <- wiki_data$entities$Q3044
library(dplyr)
label_col <- bind_rows(table_data$labels) %>% rename(label=value)
desc_col <- bind_rows(table_data$descriptions) %>% rename(description=value)
alias_col <- bind_rows(table_data$aliases) %>%
rename(alias=value) %>%
group_by(language) %>%
summarise(alias=paste(alias, collapse = ", "))
full_table <- label_col %>%
left_join(desc_col) %>%
left_join(alias_col)
输出的前几行如下所示:
> full_table
# A tibble: 157 x 4
language label description alias
<chr> <chr> <chr> <chr>
1 fr Charlemagne empereur d'Occident et roi des Francs Char~
2 en Charlemagne King of the Franks, King of Italy, and Holy Roman~ Karo~
3 it Carlo Magno re dei Franchi e dei Longobardi e primo imperator~ NA
4 ilo Karlomagno Ari dagiti Pranko ken Lombardo ken Emperador ti N~ NA