如果没有表格标签,如何在 R 中使用 html_table 抓取表格?

时间:2021-05-28 21:41:09

标签: html r web-scraping rvest finance

我一直在尝试从 yahoo.finance 中抓取表格,当我检查并找到所需部分时,代码中没有表格标记。我可以使用 html_text 函数提取数据,但它不适用于 html_table 函数。 Income Statement

[

link <- "https://finance.yahoo.com/quote/"
link <- paste0(link, tic[2], "/financials?p=", tic[2])
wahis.session <- html_session(link)
p <- wahis.session %>% 
        html_nodes(xpath = '//*[@id="Col1-1-Financials-Proxy"]/section/div[3]')

p <- html_table(p, header = F, trim = T, fill = T)

]2

1 个答案:

答案 0 :(得分:1)

“[https://stackoverflow.com/questions/58315274/r-web-scraping-yahoo-finance-after-2019-change][1]”中的讨论解决了您的问题。根据链接中的讨论,您可以获得“AAPL”的信息如下:

library(rvest)
library(tidyverse)

tic <- "AAPL"
link <- "https://finance.yahoo.com/quote/"
link <- paste0(link, tic, "/financials?p=", tic)
wahis.session <- html_session(link)
p <- wahis.session 
nodes <- p %>% html_nodes(".fi-row")

df = NULL

for(i in nodes){
  r <- list(i %>%html_nodes("[title],[data-test='fin-col']")%>%html_text())
  df <- rbind(df,as.data.frame(matrix(r[[1]], ncol = length(r[[1]]), byrow = TRUE), stringsAsFactors = FALSE))
}

matches <- str_match_all(p1%>%html_node('#Col1-1-Financials-Proxy')%>%html_text(),'\\d{1,2}/\\d{1,2}/\\d{4}')   
headers <- c('Breakdown','TTM', matches[[1]][,1]) 
names(df) <- headers