【问题标题】:Scraping wikipedia table r刮维基百科表r
【发布时间】:2017-11-29 01:59:01
【问题描述】:

试图从维基百科的人类发展指数中抓取前 8 个表(非常高、高、中、低)。

开始但得到一个零列表。我究竟做错了什么? R 新手 :(

libray(rvest)
url <- "https://en.wikipedia.org/wiki/List_of_countries_by_Human_Development_Index#Complete_list_of_countries"
webpage <- read_html(url)

hdi_tables <- html_nodes(webpage, 'table')

head(hdi_tables, n = 10)

scrape <- url %>%
  read_html() %>%
  html_nodes(xpath = '//*[@id="mw-content-text"]/div/div[5]/table/tbody/tr/td[1]/table') %>%
  html_table()

head(scrape, n=10)

【问题讨论】:

  • 可能更容易得到原始数据from the source。您可以选择 HDI 并下载 CSV 文件,直到 2015 年。维基百科上的表格是 2016 年的估计值。

标签: html r screen-scraping rvest


【解决方案1】:

我认为使用original data source 会更容易:

在两个下拉选择列表中选择“人类发展指数 (HDI)”,然后单击“下载数据”链接以获取名为 Human Development Index (HDI).csv 的 CSV 文件。

将其读入 R:

library(tidyverse)
Human_Development_Index_HDI_ <- read_csv("path/to/Human Development Index (HDI).csv", 
                                         skip = 1)

您可以重塑数据,获取 2015 年的值并将国家/地区分类为低、中、高或非常高:

hdi <- Human_Development_Index_HDI_ %>% 
  gather(Year, HDI, -`HDI Rank (2015)`, -Country) %>% 
  filter(Year == "2015") %>% 
  na.omit() %>% 
  mutate(Year = as.numeric(Year), 
         classification = cut(HDI,
                              breaks = c(0, 0.549, 0.699, 0.799, 1), 
                              labels = c("low", "medium", "high", "very_high")))

hdi

# A tibble: 188 x 5
   `HDI Rank (2015)`             Country  Year   HDI classification
               <int>               <chr> <dbl> <dbl>         <fctr>
 1               169         Afghanistan  2015 0.479            low
 2                75             Albania  2015 0.764           high
 3                83             Algeria  2015 0.745           high
 4                32             Andorra  2015 0.858      very_high
 5               150              Angola  2015 0.533            low
 6                62 Antigua and Barbuda  2015 0.786           high
 7                45           Argentina  2015 0.827      very_high
 8                84             Armenia  2015 0.743           high
 9                 2           Australia  2015 0.939      very_high
10                24             Austria  2015 0.893      very_high
# ... with 178 more rows

如果您想复制 Wikipedia 表中的“与上一年相比的变化”值,您也可以更改过滤器以获取 2014 年的值。

【讨论】:

    【解决方案2】:

    如果您对解析维基百科标记语言没问题,您可以尝试使用WikipediR 来获取页面的标记(通过浏览文档,尝试将as_wikitext 设置为true 的page_content)。然后你会得到一些看起来像这样的行:

    |  1 || {{steady}} ||style="text-align:left"| {{flag|Norway}} || 0.949 || {{increase}} 0.001
    

    这应该可以在 R 中使用 strsplit 或其他东西进行解析。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-16
      • 2011-08-31
      • 1970-01-01
      • 2019-05-24
      • 1970-01-01
      相关资源
      最近更新 更多