【问题标题】:Parsing table and urls in R with rvest使用 rvest 在 R 中解析表和 url
【发布时间】:2021-03-22 20:57:30
【问题描述】:

抱歉,还有一个问题。

我需要这张表中的数据:http://rspp.ru/tables/non-financial-reports-library/ 它包含俄罗斯公司的非财务报告。刮掉它是合法的。出于研究目的,我需要进行一些文本挖掘。

理想情况下,我需要以下输出:公司 - 年份 - 报告 URL。

我正在尝试抓取它,但我无法将 URL 与公司和年份数据对应起来。这是我的脚本:

library(rvest)
library(dplyr)

url = "http://rspp.ru/tables/non-financial-reports-library/"

page = read_html(url)

# table
tab = page %>% 
  html_node("table") %>% 
  html_table(fill = T) 

# links
links = page %>% 
  html_node("table") %>% 
  html_nodes("a") %>% 
  html_attr("href")

你能帮忙吗?

【问题讨论】:

    标签: r screen-scraping rvest scrape


    【解决方案1】:

    桌子不规则。一个丑陋的方法是通过使用colspanrowspan 属性值分别在列和行中重建表,将表扩展为常规数据框。

    然后您可以添加适当的标题并考虑合并的单元格,我只是在适用的年份重复相同的 URL。我确实抓住了给定报告所涵盖年份的文本描述,例如2007-2009(在带有链接的单元格中看到),但不要像标题行中使用的年份那样输出它。

    library(rvest)
    library(stringr)
    
    url <- 'http://rspp.ru/tables/non-financial-reports-library/'
    page <- read_html(url)
    headers <- page %>% html_nodes('.company-report-table .register-table__row:nth-child(1) th')%>%html_text()
    companies <- page %>% html_nodes('.company-report-table .register-table__row td:nth-child(1) span')%>%html_text()
    body_rows <- page %>% html_nodes('.register-table__row ~ .register-table__row')
    df <- data.frame(matrix(NA_character_, nrow = length(body_rows), ncol = length(headers)))
    n <- 0
    
    for(row in seq_along(body_rows)){
      curr_row <-  body_rows[[row]] 
      rspan <- curr_row %>% html_node('td') %>% html_attr('rowspan') %>% as.integer() #rspan tells us how many rows per company
      
      if(!is.na(rspan)){
        n <- n + 1
        title <- companies[[n]]
      }
      df[row,1] = title 
      # handle other columns excluding first
      columns_minus_first <- curr_row %>% html_nodes('td:not(:nth-child(1))') # not always 21 range 10 > 21 but we use colspan to expand to 21
      c <- 1
      
      for(column in seq_along(columns_minus_first)){
        curr_col <- columns_minus_first[[column]]
        cspan <- curr_col %>% html_attr('colspan') %>% as.integer() #use cspan value to determine how many years report covers
        
        if(!is.na(cspan)){
          link <- paste0('http://rspp.ru', curr_col %>% html_node('a') %>% html_attr('href'))
          year <- str_extract(curr_col %>% html_text() ,'\\b[0-9-]{4,9}\\b') #purists may want a tighter regex for year spans
          
          for(i in seq_along(cspan)){ #we will start writing out from col 2 as first col is the company name
            df[row,i+c] <- link #repeats for each year covered by report (could alter this for only first)
          }
        }
        c <- c + 1
      }
    }
    
    colnames(df) <- headers
    df <- tibble(df)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-21
      • 2017-11-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2017-04-01
      相关资源
      最近更新 更多