【问题标题】:Turning a table in HTML into a data frame将 HTML 中的表格转换为数据框
【发布时间】:2018-01-02 16:29:06
【问题描述】:

我正在尝试从 Wikipedia 上抓取表格,但我陷入了僵局。我以 FIFA 2014 世界杯的阵容为例。在这种情况下,我想从“2014 FIFA 世界杯阵容”页面的目录中提取参与国家的列表并将它们存储为向量。以下是我的成绩:

library(tidyverse)
library(rvest)
library(XML)
library(RCurl)

(Countries <- read_html("https://en.wikipedia.org/wiki/2014_FIFA_World_Cup_squads") %>% 
  html_node(xpath = '//*[@id="toc"]/ul') %>% 
  htmlTreeParse() %>%
  xmlRoot())

这会吐出一堆我不会在这里复制/粘贴的 HTML 代码。我特别希望提取带有标签&lt;span class="toctext"&gt; 的所有行,例如“A 组”、“巴西”、“喀麦隆”等,并将它们保存为向量。什么功能可以做到这一点?

【问题讨论】:

    标签: html r web-scraping


    【解决方案1】:

    您可以使用html_text()从节点读取文本

    url <- "https://en.wikipedia.org/wiki/2014_FIFA_World_Cup_squads"
    toc <- url %>%
        read_html() %>%
        html_node(xpath = '//*[@id="toc"]') %>%
        html_text()
    

    这为您提供了一个单一的字符向量。然后,您可以拆分 \n 字符以将结果作为向量提供(并且您可以清除空白)

    contents <- strsplit(toc, "\n")[[1]]
    
    contents[contents != ""]
    
    # [1] "Contents"                                   "1 Group A"                                  "1.1 Brazil"                                
    # [4] "1.2 Cameroon"                               "1.3 Croatia"                                "1.4 Mexico"                                
    # [7] "2 Group B"                                  "2.1 Australia"                              "2.2 Chile"                                 
    # [10] "2.3 Netherlands"                            "2.4 Spain"                                  "3 Group C"                                 
    # [13] "3.1 Colombia"                               "3.2 Greece"                                 "3.3 Ivory Coast"                           
    # [16] "3.4 Japan"                                  "4 Group D"                                  "4.1 Costa Rica"                            
    # [19] "4.2 England"                                "4.3 Italy"                                  "4.4 Uruguay"                               
    # ---
    # etc
    

    通常,要读取 html 文档中的表格,您可以使用 html_table() 函数,但在这种情况下,不会读取目录。

    url %>% 
        read_html() %>%
        html_table()
    

    【讨论】:

      猜你喜欢
      • 2015-11-30
      • 2019-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多