【问题标题】:Webscraping html table using R使用 R 抓取 html 表格
【发布时间】:2016-08-19 08:05:20
【问题描述】:

我已经从 Stackoverflow 的用户那里得到了一些帮助,试图解决这个问题。然而,我遇到了新的麻烦:

URL <- "http://karakterstatistik.stads.ku.dk/Histogram/ASOB05038E/Summer-2015"
pg <- read_html(URL)

get_val <- function(x, label) {
xpath <- sprintf(".//table/tr/td[contains(., '%s')][1]/following-sibling::td", label)
html_nodes(x, xpath=xpath) %>% 
html_text() %>% 
trimws()
}

library("stringr")
trimmed = get_val(pg, "Karakter") %>% 
  str_replace_all(pattern = "\\n|\\t|\\r" , 
              replacement = "")
trimmed

我想获取重考和考试的考试结果,但由于两个表的标题相同,R 只取重考的值。 具体来说,我想在标题 Resultater 下的两个表格中的成绩 12、10、7、4、02、00、-3 旁边获得“Antal”列

任何帮助将不胜感激! :)

【问题讨论】:

    标签: html r screen-scraping


    【解决方案1】:
    results <- html_nodes(pg, xpath=".//td[@style='width: 50%;' and 
                                           descendant::h3[contains(text(), 'Resultater')]]/table")
    
    html_table(results[[1]])
    ##   Karakter Antal    Antal
    ## 1       12    11  (9,6 %)
    ## 2       10    48 (41,7 %)
    ## 3        7    41 (35,7 %)
    ## 4        4     4  (3,5 %)
    ## 5       02     1  (0,9 %)
    ## 6       00     1  (0,9 %)
    ## 7       -3     4  (3,5 %)
    ## 8  Ej mødt     5  (4,3 %)
    
    html_table(results[[2]])
    ##   Karakter Antal    Antal
    ## 1       12     0  (0,0 %)
    ## 2       10     0  (0,0 %)
    ## 3        7     1  (9,1 %)
    ## 4        4     1  (9,1 %)
    ## 5       02     1  (9,1 %)
    ## 6       00     1  (9,1 %)
    ## 7       -3     0  (0,0 %)
    ## 8  Ej mødt     7 (63,6 %)
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 2021-06-07
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 2018-01-05
      • 1970-01-01
      相关资源
      最近更新 更多